1: # The LearningOnline Network with CAPA
2: # Routines for messaging
3: #
4: # $Id: lonmsg.pm,v 1.239.2.4.2.1 2023/01/23 17:52:06 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, $toperm, $sentmessage, $nosentstore, $recipid, $attachmenturl, $permresults, $senthide)>:
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,$permresults,$senthide)>:
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,$recuser,$recdomain,
222: $msgid,$type,$crsmsgid,$symb,$error,$recipid,$senthide,$origmsgid)=@_;
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: if ($senthide) {
233: foreach my $item ($subject,$message) {
234: if ($item ne '') {
235: $item = 'Not shown due to IP block';
236: }
237: }
238: if ($attachmenturl ne '') {
239: $attachmenturl = '';
240: }
241: if ($citation ne '') {
242: $citation = '';
243: }
244: if ($msgid ne '') {
245: $msgid = '';
246: }
247: }
248: my $course_context = &get_course_context();
249: my $now=time;
250: my $ip = &Apache::lonnet::get_requestor_ip();
251: my $msgcount = &get_uniq();
252: unless(defined($msgid)) {
253: $msgid = &buildmsgid($now,$subject,$env{'user.name'},$env{'user.domain'},
254: $msgcount,$course_context,$symb,$error,$$);
255: }
256: my $result = '<sendername>'.$env{'user.name'}.'</sendername>'.
257: '<senderdomain>'.$env{'user.domain'}.'</senderdomain>'.
258: '<subject>'.$subject.'</subject>'.
259: '<time>'.&Apache::lonlocal::locallocaltime($now).'</time>';
260: if (defined($crsmsgid)) {
261: $result.= '<courseid>'.$course_context.'</courseid>'.
262: '<coursesec>'.$env{'request.course.sec'}.'</coursesec>'.
263: '<msgid>'.$msgid.'</msgid>'.
264: '<coursemsgid>'.$crsmsgid.'</coursemsgid>'.
265: '<message>'.$message.'</message>';
266: return ($msgid,$result);
267: }
268: $result .= '<servername>'.$ENV{'SERVER_NAME'}.'</servername>'.
269: '<host>'.$ENV{'HTTP_HOST'}.'</host>'.
270: '<client>'.$ip.'</client>'.
271: '<browsertype>'.$env{'browser.type'}.'</browsertype>'.
272: '<browseros>'.$env{'browser.os'}.'</browseros>'.
273: '<browserversion>'.$env{'browser.version'}.'</browserversion>'.
274: '<browsermathml>'.$env{'browser.mathml'}.'</browsermathml>'.
275: '<browserraw>'.$ENV{'HTTP_USER_AGENT'}.'</browserraw>'.
276: '<courseid>'.$course_context.'</courseid>'.
277: '<coursesec>'.$env{'request.course.sec'}.'</coursesec>'.
278: '<role>'.$env{'request.role'}.'</role>'.
279: '<resource>'.$env{'request.filename'}.'</resource>'.
280: '<msgid>'.$msgid.'</msgid>';
281: if (defined($env{'form.group'})) {
282: $result .= '<group>'.$env{'form.group'}.'</group>';
283: }
284: if (ref($recuser) eq 'ARRAY') {
285: for (my $i=0; $i<@{$recuser}; $i++) {
286: if ($type eq 'dcmail') {
287: my ($username,$email) = split(/:/,$$recuser[$i]);
288: $username = &unescape($username);
289: $email = &unescape($email);
290: $username = &HTML::Entities::encode($username,'<>&"');
291: $email = &HTML::Entities::encode($email,'<>&"');
292: $result .= '<recipient username="'.$username.'">'.
293: $email.'</recipient>';
294: } else {
295: $result .= '<recuser>'.$$recuser[$i].'</recuser>'.
296: '<recdomain>'.$$recdomain[$i].'</recdomain>';
297: }
298: }
299: } else {
300: $result .= '<recuser>'.$recuser.'</recuser>'.
301: '<recdomain>'.$recdomain.'</recdomain>';
302: }
303: $result .= '<message>'.$message.'</message>';
304: if (defined($citation)) {
305: $result.='<citation>'.$citation.'</citation>';
306: }
307: if (defined($baseurl)) {
308: $result.= '<baseurl>'.$baseurl.'</baseurl>';
309: }
310: if (defined($attachmenturl)) {
311: $result.= '<attachmenturl>'.$attachmenturl.'</attachmenturl>';
312: }
313: if (defined($symb)) {
314: $result.= '<symb>'.$symb.'</symb>';
315: if ($course_context ne '') {
316: if ($course_context eq $env{'request.course.id'}) {
317: my $resource_title = &Apache::lonnet::gettitle($symb);
318: if (defined($resource_title)) {
319: $result .= '<resource_title>'.$resource_title.'</resource_title>';
320: }
321: }
322: }
323: }
324: if (defined($recipid)) {
325: $result.= '<recipid>'.$recipid.'</recipid>';
326: }
327: if ($env{'form.can_reply'} eq 'N') {
328: $result .= '<noreplies>1</noreplies>';
329: }
330: if ($env{'form.reply_to_addr'}) {
331: my ($replytoname,$replytodom) = split(/:/,$env{'form.reply_to_addr'});
332: if (!($replytoname eq $env{'user.name'} && $replytodom eq $env{'user.domain'})) {
333: if (&Apache::lonnet::homeserver($replytoname,$replytodom) ne 'no_host') {
334: $result .= '<replytoaddr>'.$env{'form.reply_to_addr'}.'</replytoaddr>';
335: }
336: }
337: }
338: if ($senthide) {
339: $result .= '<senthide>$origmsgid</senthide>';
340: }
341: return ($msgid,$result);
342: }
343:
344: sub get_course_context {
345: my $course_context;
346: my $msgkey;
347: if (defined($env{'form.replyid'})) {
348: $msgkey = $env{'form.replyid'};
349: } elsif (defined($env{'form.forwid'})) {
350: $msgkey = $env{'form.forwid'}
351: } elsif (defined($env{'form.multiforwid'})) {
352: $msgkey = $env{'form.multiforwid'};
353: }
354: if ($msgkey ne '') {
355: my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid)=
356: split(/\:/,&unescape($msgkey));
357: $course_context = $origcid;
358: }
359: foreach my $key (keys(%env)) {
360: if ($key=~/^form\.(rep)?rec\_(.*)$/) {
361: my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid) =
362: split(/\:/,&unescape($2));
363: $course_context = $origcid;
364: last;
365: }
366: }
367: if ($course_context eq '') {
368: $course_context = $env{'request.course.id'};
369: }
370: return $course_context;
371: }
372:
373:
374: sub unpackagemsg {
375: my ($message,$notoken,$noattachmentlink)=@_;
376: my %content=();
377: my $parser=HTML::TokeParser->new(\$message);
378: my $token;
379: while ($token=$parser->get_token) {
380: if ($token->[0] eq 'S') {
381: my $entry=$token->[1];
382: my $value=$parser->get_text('/'.$entry);
383: if (($entry eq 'recuser') || ($entry eq 'recdomain')) {
384: push(@{$content{$entry}},$value);
385: } elsif ($entry eq 'recipient') {
386: my $username = $token->[2]{'username'};
387: $username = &HTML::Entities::decode($username,'<>&"');
388: $content{$entry}{$username} = $value;
389: } else {
390: $content{$entry}=$value;
391: }
392: }
393: }
394: if (!exists($content{'recuser'})) { $content{'recuser'} = []; }
395: if (($content{'attachmenturl'}) && (!$noattachmentlink)) {
396: my ($fname)=($content{'attachmenturl'}=~m|/([^/]+)$|);
397: if ($notoken) {
398: $content{'message'}.='<p>'.&mt('Attachment').': <tt>'.$fname.'</tt>';
399: } else {
400: &Apache::lonnet::allowuploaded('/adm/msg',
401: $content{'attachmenturl'});
402: $content{'message'}.='<p>'.&mt('Attachment').
403: ': <a href="'.$content{'attachmenturl'}.'"><tt>'.
404: $fname.'</tt></a>';
405: }
406: }
407: return %content;
408: }
409:
410:
411: sub buildmsgid {
412: my ($now,$subject,$uname,$udom,$msgcount,$course_context,$symb,$error,$pid) = @_;
413: $subject=&escape($subject);
414: $symb = &escape($symb);
415: return(&escape($now.':'.$subject.':'.$uname.':'.
416: $udom.':'.$msgcount.':'.$course_context.':'.$pid.':'.$symb.':'.$error));
417: }
418:
419: sub unpackmsgid {
420: my ($msgid,$folder,$skipstatus,$status_cache,$onlycid)=@_;
421: $msgid=&unescape($msgid);
422: my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$fromcid,
423: $processid,$symb,$error) = split(/\:/,&unescape($msgid));
424: if (!defined($processid)) { $fromcid = ''; }
425: if (($onlycid) && ($onlycid ne $fromcid)) {
426: return ($sendtime,'',$fromname,$fromdomain,'',$fromcid,'',$error);
427: }
428: $shortsubj = &unescape($shortsubj);
429: $shortsubj = &HTML::Entities::decode($shortsubj);
430: $symb = &unescape($symb);
431: if (!defined($processid)) { $fromcid = ''; }
432: my %status=();
433: unless ($skipstatus) {
434: if (ref($status_cache)) {
435: $status{$msgid} = $status_cache->{$msgid};
436: } else {
437: my $suffix=&foldersuffix($folder);
438: %status=&Apache::lonnet::get('email_status'.$suffix,[$msgid]);
439: }
440: if ($status{$msgid}=~/^error\:/) { $status{$msgid}=''; }
441: unless ($status{$msgid}) { $status{$msgid}='new'; }
442: }
443: return ($sendtime,$shortsubj,$fromname,$fromdomain,$status{$msgid},$fromcid,$symb,$error);
444: }
445:
446:
447: sub sendemail {
448: my ($to,$subject,$body,$to_uname,$to_udom,$user_lh)=@_;
449: my $senderaddress='';
450: my $replytoaddress='';
451: my $msgsent;
452: if ($env{'form.can_reply'} eq 'N') {
453: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
454: my $hostname = &Apache::lonnet::hostname($lonhost);
455: $replytoaddress = 'do-not-reply@'.$hostname;
456: } else {
457: my %senderemails;
458: my $have_sender;
459: if ($env{'form.reply_to_addr'}) {
460: my ($replytoname,$replytodom) = split(/:/,$env{'form.reply_to_addr'});
461: if (!($replytoname eq $env{'user.name'} && $replytodom eq $env{'user.domain'})) {
462: if (&Apache::lonnet::homeserver($replytoname,$replytodom) ne 'no_host') {
463: %senderemails =
464: &Apache::loncommon::getemails($replytoname,$replytodom);
465: $have_sender = 1;
466: }
467: }
468: }
469: if (!$have_sender) {
470: %senderemails=&Apache::loncommon::getemails();
471: }
472: foreach my $type ('permanentemail','critnotification','notification') {
473: if ($senderemails{$type}) {
474: ($senderaddress) = split(/,/,$senderemails{$type});
475: last if ($senderaddress);
476: }
477: }
478: }
479: $body=
480: "*** ".&mt_user($user_lh,'This is an automatic e-mail generated by the LON-CAPA system.')."\n".
481: "*** ".($senderaddress?&mt_user($user_lh,'You can reply to this e-mail'):&mt_user($user_lh,'Please do not reply to this address.')."\n*** ".
482: &mt_user($user_lh,'A reply will not be received by the recipient!'))."\n\n".$body;
483:
484: my $msg = new Mail::Send;
485: $msg->to($to);
486: $msg->subject('[LON-CAPA] '.$subject);
487: if ($replytoaddress) {
488: $msg->add('Reply-to',$replytoaddress);
489: }
490: if ($senderaddress) {
491: $msg->add('From',$senderaddress);
492: }
493: $msg->add('Content-type','text/plain; charset=UTF-8');
494: if (my $fh = $msg->open()) {
495: print $fh $body;
496: $fh->close;
497: $msgsent = 1;
498: }
499: return $msgsent;
500: }
501:
502: # ==================================================== Send notification emails
503:
504: sub sendnotification {
505: my ($to,$touname,$toudom,$subj,$crit,$text,$msgid)=@_;
506: my $sender=$env{'environment.firstname'}.' '.$env{'environment.lastname'};
507: unless ($sender=~/\w/) {
508: $sender=$env{'user.name'}.':'.$env{'user.domain'};
509: }
510: my $critical=($crit?' critical':'');
511: my $numsent = 0;
512:
513: $text=~s/\<\;/\</gs;
514: $text=~s/\>\;/\>/gs;
515: my $touhome = &Apache::lonnet::homeserver($touname,$toudom);
516: my $url = &Apache::lonnet::url_prefix('',$toudom,$touhome,'email').
517: '/adm/email?username='.$touname.'&domain='.$toudom.
518: '&display='.&escape($msgid);
519: my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid,
520: $symb,$error) = &Apache::lonmsg::unpackmsgid($msgid);
521: my ($coursetext,$body,$bodybegin,$bodysubj,$bodyend);
522: my $user_lh = &Apache::loncommon::user_lang($touname,$toudom,$fromcid);
523: if ($fromcid ne '') {
524: $coursetext = "\n".&mt_user($user_lh,'Course').': ';
525: if ($env{'course.'.$fromcid.'.description'} ne '') {
526: $coursetext .= $env{'course.'.$fromcid.'.description'};
527: } else {
528: my %coursehash = &Apache::lonnet::coursedescription($fromcid,);
529: if ($coursehash{'description'} ne '') {
530: $coursetext .= $coursehash{'description'};
531: }
532: }
533: $coursetext .= "\n\n";
534: }
535: my @recipients = split(/,/,$to);
536: $bodybegin = $coursetext.
537: &mt_user($user_lh,
538: 'You received a'.$critical.' message from [_1] in LON-CAPA.',$sender).' ';
539: $bodysubj = &mt_user($user_lh,'The subject is
540:
541: [_1]
542:
543: ',$subj)."\n".
544: '=== '.&mt_user($user_lh,'Excerpt')." ============================================================
545: ";
546: $bodyend = "
547: ========================================================================
548:
549: ".&mt_user($user_lh,'Use
550:
551: [_1]
552:
553: to access the full message.',$url);
554: my %userenv = &Apache::lonnet::get('environment',['notifywithhtml'],$toudom,$touname);
555: my $subject = &mt_user($user_lh,"'New'$critical message from [_1]",$sender);
556: unless ($subj eq '') {
557: $subject = $subj;
558: }
559:
560: my ($blocked,$blocktext,$clientip);
561: $clientip = &Apache::lonnet::get_requestor_ip();
562: if (!$crit) {
563: my %setters;
564: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
565: &Apache::loncommon::blockcheck(\%setters,'com',$clientip,$touname,$toudom);
566: if ($startblock && $endblock) {
567: $blocked = 1;
568: my $showstart = &Apache::lonlocal::locallocaltime($startblock);
569: my $showend = &Apache::lonlocal::locallocaltime($endblock);
570: $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);
571: } elsif ($by_ip) {
572: $blocked = 1;
573: $blocktext = &mt_user($user_lh,'LON-CAPA messages sent to you will be inaccessible from your IP address [_1], because communication is being blocked for certain IP address(es).',$clientip);
574: }
575: }
576: if ($userenv{'notifywithhtml'} ne '') {
577: my @htmlexcerpt = split(/,/,$userenv{'notifywithhtml'});
578: my $htmlfree = &make_htmlfree($text);
579: foreach my $addr (@recipients) {
580: if ($blocked) {
581: $body = $bodybegin."\n".$blocktext."\n".$bodyend;
582: } else {
583: my $sendtext;
584: if (!grep/^\Q$addr\E/,@htmlexcerpt) {
585: $sendtext = $htmlfree;
586: } else {
587: $sendtext = $text;
588: }
589: $body = $bodybegin.$bodysubj.$sendtext.$bodyend;
590: }
591: if (&sendemail($addr,$subject,$body,$touname,$toudom,$user_lh)) {
592: $numsent ++;
593: }
594: }
595: } else {
596: if ($blocked) {
597: $body = $bodybegin."\n".$blocktext."\n".$bodyend;
598: } else {
599: my $htmlfree = &make_htmlfree($text);
600: $body = $bodybegin.$bodysubj.$htmlfree.$bodyend;
601: }
602: if (&sendemail($to,$subject,$body,$touname,$toudom,$user_lh)) {
603: $numsent ++;
604: }
605: }
606: return $numsent;
607: }
608:
609: sub make_htmlfree {
610: my ($text) = @_;
611: $text =~ s/\<\/*[^\>]+\>//gs;
612: $text = &HTML::Entities::decode($text);
613: $text = &Encode::encode('utf8',$text);
614: return $text;
615: }
616:
617: sub mynewmail{
618: &newmail();
619: return $env{'user.mailcheck.lastnewmessagetime'} > $env{'user.mailcheck.lastvisit'};
620: }
621:
622:
623: sub newmail {
624: if ((time-$env{'user.mailcheck.time'})>300) {
625: my %what=&Apache::lonnet::get('email_status',['recnewemail']);
626: &Apache::lonnet::appenv({'user.mailcheck.time'=>time});
627: &Apache::lonnet::appenv({'user.mailcheck.lastnewmessagetime'=> $what{'recnewemail'}});
628: if ($what{'recnewemail'}>0) { return 1; }
629: }
630: return 0;
631: }
632:
633:
634:
635: sub author_res_msg {
636: my ($filename,$message)=@_;
637: unless ($message) { return 'empty'; }
638: $filename=&Apache::lonnet::declutter($filename);
639: my ($domain,$author,@dummy)=split(/\//,$filename);
640: my $homeserver=&Apache::lonnet::homeserver($author,$domain);
641: if ($homeserver ne 'no_host') {
642: my $id=unpack("%32C*",$message);
643: $message .= " <p>This error occurred on machine ".
644: $Apache::lonnet::perlvar{'lonHostID'}."</p>";
645: my $msgid;
646: ($msgid,$message)=&packagemsg($filename,$message);
647: return &Apache::lonnet::reply('put:'.$domain.':'.$author.
648: ':nohist_res_msgs:'.
649: &escape($filename.'_'.$id).'='.
650: &escape($message),$homeserver);
651: }
652: return 'no_host';
653: }
654:
655:
656:
657: sub retrieve_author_res_msg {
658: my $url=shift;
659: $url=&Apache::lonnet::declutter($url);
660: my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
661: my %errormsgs=&Apache::lonnet::dump('nohist_res_msgs',$domain,$author);
662: my $msgs='';
663: foreach my $msg (keys(%errormsgs)) {
664: if ($msg =~ /^\Q$url\E\_\d+$/) {
665: my %content=&unpackagemsg($errormsgs{$msg});
666: $msgs.='<p><img src="/adm/lonMisc/bomb.gif" /><b>'.
667: $content{'time'}.'</b>: '.$content{'message'}.
668: '<br /></p>';
669: }
670: }
671: return $msgs;
672: }
673:
674:
675:
676:
677:
678: sub del_url_author_res_msg {
679: my $url=shift;
680: $url=&Apache::lonnet::declutter($url);
681: my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
682: my @delmsgs=();
683: foreach my $msg (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
684: if ($msg =~ /^\Q$url\E\_\d+$/) {
685: push (@delmsgs,$msg);
686: }
687: }
688: return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
689: }
690:
691:
692: sub clear_author_res_msg {
693: my $url=shift;
694: $url=&Apache::lonnet::declutter($url);
695: my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
696: my @delmsgs=();
697: foreach my $msg (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
698: if ($msg =~ /^\Q$url\E/) {
699: push (@delmsgs,$msg);
700: }
701: }
702: return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
703: }
704:
705:
706:
707: sub all_url_author_res_msg {
708: my ($author,$domain)=@_;
709: my %returnhash=();
710: foreach my $msg (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
711: $msg =~ /^(.+)\_\d+/;
712: $returnhash{$1}=1;
713: }
714: return %returnhash;
715: }
716:
717:
718: sub store_instructor_comment {
719: my ($msg,$uname,$udom) = @_;
720: my $cid = $env{'request.course.id'};
721: my $cnum = $env{'course.'.$cid.'.num'};
722: my $cdom = $env{'course.'.$cid.'.domain'};
723: my $subject= &mt('Record').' ['.$uname.':'.$udom.']';
724: my $result = &user_normal_msg_raw($cnum,$cdom,$subject,$msg);
725: if ($result eq 'ok' || $result eq 'con_delayed') {
726:
727: }
728: return $result;
729: }
730:
731:
732: sub user_crit_msg_raw {
733: my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
734: $nosentstore,$recipid,$attachmenturl,$permresults,$senthide)=@_;
735: # Check if allowed missing
736: my ($status,$packed_message);
737: my $msgid='undefined';
738: unless (($message)&&($user)&&($domain)) { $status='empty'; };
739: my $text=$message;
740: my $homeserver=&Apache::lonnet::homeserver($user,$domain);
741: if ($homeserver ne 'no_host') {
742: ($msgid,$packed_message)=&packagemsg($subject,$message,undef,undef,
743: $attachmenturl,undef,undef,undef,undef,undef,
744: undef,undef,$recipid);
745: if ($sendback) { $packed_message.='<sendback>true</sendback>'; }
746: $status=&Apache::lonnet::cput('critical', {$msgid => $packed_message},
747: $domain,$user);
748: if (defined($sentmessage)) {
749: $$sentmessage = $packed_message;
750: }
751: if (!$nosentstore) {
752: my ($sentmsgid,$packed_message_no_citation) =
753: &packagemsg($subject,$message,undef,undef,$attachmenturl,$user,
754: $domain,$msgid,undef,undef,undef,undef,undef,$senthide,$msgid);
755: if ($status eq 'ok' || $status eq 'con_delayed') {
756: if ($senthide && $sentmsgid) {
757: &store_sent_mail($sentmsgid,$packed_message_no_citation);
758: } else {
759: &store_sent_mail($msgid,$packed_message_no_citation);
760: }
761: }
762: }
763: } else {
764: $status='no_host';
765: }
766:
767: # Notifications
768: my %userenv = &Apache::loncommon::getemails($user,$domain);
769: my $critnotify = $userenv{'critnotification'};
770: my $permemail = $userenv{'permanentemail'};
771: my $numcrit = 0;
772: my $numperm = 0;
773: my $permlogmsgstatus;
774: if ($critnotify) {
775: $numcrit = &sendnotification($critnotify,$user,$domain,$subject,1,$text,$msgid);
776: }
777: if ($toperm && $permemail) {
778: if ($critnotify && $numcrit) {
779: if (grep(/^\Q$permemail\E/,split(/,/,$critnotify))) {
780: $numperm = 1;
781: }
782: }
783: unless ($numperm) {
784: $numperm = &sendnotification($permemail,$user,$domain,$subject,1,$text,$msgid);
785: }
786: }
787: if ($toperm) {
788: $permlogmsgstatus = '. Perm. email log status '.
789: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
790: "Perm. e-mail count $numperm for $user at $domain");
791: if (ref($permresults) eq 'HASH') {
792: $permresults->{"$user:$domain"} = $numperm;
793: }
794: }
795: # Log this
796: &Apache::lonnet::logthis(
797: 'Sending critical '.$msgid.
798: ', log status: '.
799: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
800: $env{'user.home'},
801: 'Sending critical '.$msgid.' to '.$user.' at '.$domain.' with status '
802: .$status).$permlogmsgstatus);
803: return $status;
804: }
805:
806:
807:
808: sub user_crit_msg {
809: my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
810: $nosentstore,$recipid,$attachmenturl,$permresults,$senthide)=@_;
811: my @status;
812: my %userenv = &Apache::lonnet::get('environment',['msgforward'],
813: $domain,$user);
814: my $msgforward=$userenv{'msgforward'};
815: if ($msgforward) {
816: foreach my $addr (split(/\,/,$msgforward)) {
817: my ($forwuser,$forwdomain)=split(/\:/,$addr);
818: push(@status,
819: &user_crit_msg_raw($forwuser,$forwdomain,$subject,$message,
820: $sendback,$toperm,$sentmessage,$nosentstore,
821: $recipid,$attachmenturl,$permresults,$senthide));
822: }
823: } else {
824: push(@status,
825: &user_crit_msg_raw($user,$domain,$subject,$message,$sendback,
826: $toperm,$sentmessage,$nosentstore,$recipid,
827: $attachmenturl,$permresults,$senthide));
828: }
829: if (wantarray) {
830: return @status;
831: }
832: return join(' ',@status);
833: }
834:
835:
836: sub user_crit_received {
837: my $msgid=shift;
838: my %message=&Apache::lonnet::get('critical',[$msgid]);
839: my %contents=&unpackagemsg($message{$msgid},1);
840: my $destname = $contents{'sendername'};
841: my $destdom = $contents{'senderdomain'};
842: if ($contents{'replytoaddr'}) {
843: my ($repname,$repdom) = split(/:/,$contents{'replytoaddr'});
844: if (&Apache::lonnet::homeserver($repname,$repdom) ne 'no_host') {
845: $destname = $repname;
846: $destdom = $repdom;
847: }
848: }
849: my $status='rec: '.($contents{'sendback'}?
850: &user_normal_msg($destname,$destdom,&mt('Receipt').': '.$env{'user.name'}.
851: ' '.&mt('at').' '.$env{'user.domain'}.', '.
852: $contents{'subject'},&mt('User').' '.$env{'user.name'}.
853: ' '.&mt('at').' '.$env{'user.domain'}.
854: ' acknowledged receipt of message'."\n".' "'.
855: $contents{'subject'}.'"'."\n".&mt('dated').' '.
856: $contents{'time'}.".\n"
857: ):'no msg req');
858: $status.=' trans: '.
859: &Apache::lonnet::put(
860: 'nohist_email',{$contents{'msgid'} => $message{$msgid}});
861: $status.=' del: '.
862: &Apache::lonnet::del('critical',[$contents{'msgid'}]);
863: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
864: $env{'user.home'},'Received critical message '.
865: $contents{'msgid'}.
866: ', '.$status);
867: return $status;
868: }
869:
870:
871:
872:
873: sub user_normal_msg_raw {
874: my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
875: $toperm,$currid,$newid,$sentmessage,$crsmsgid,$symb,$restitle,
876: $error,$nosentstore,$recipid,$permresults,$senthide)=@_;
877: # Check if allowed missing
878: my ($status,$packed_message);
879: my $msgid='undefined';
880: my $text=$message;
881: unless (($message)&&($user)&&($domain)) { $status='empty'; };
882: my $homeserver=&Apache::lonnet::homeserver($user,$domain);
883: if ($homeserver ne 'no_host') {
884: ($msgid,$packed_message)=
885: &packagemsg($subject,$message,$citation,$baseurl,
886: $attachmenturl,$user,$domain,$currid,
887: undef,$crsmsgid,$symb,$error,$recipid);
888:
889: # Store in user folder
890: $status=
891: &Apache::lonnet::cput('nohist_email',{$msgid => $packed_message},
892: $domain,$user);
893: # Save new message received time
894: &Apache::lonnet::put
895: ('email_status',{'recnewemail'=>time},$domain,$user);
896: # Into sent-mail folder if sent mail storage required
897: if (!$nosentstore) {
898: my ($sentmsgid,$packed_message_no_citation) =
899: &packagemsg($subject,$message,undef,$baseurl,$attachmenturl,
900: $user,$domain,$currid,undef,$crsmsgid,$symb,$error,
901: undef,$senthide,$msgid);
902: if ($status eq 'ok' || $status eq 'con_delayed') {
903: if ($senthide && $sentmsgid) {
904: &store_sent_mail($sentmsgid,$packed_message_no_citation);
905: } else {
906: &store_sent_mail($msgid,$packed_message_no_citation);
907: }
908: }
909: }
910: if (ref($newid) eq 'SCALAR') {
911: $$newid = $msgid;
912: }
913: if (ref($sentmessage) eq 'SCALAR') {
914: $$sentmessage = $packed_message;
915: }
916: # Notifications
917: my %userenv = &Apache::loncommon::getemails($user,$domain);
918: my $notify = $userenv{'notification'};
919: my $permemail = $userenv{'permanentemail'};
920: my $numnotify = 0;
921: my $numperm = 0;
922: my $permlogmsgstatus;
923: if ($notify) {
924: $numnotify = &sendnotification($notify,$user,$domain,$subject,0,$text,$msgid);
925: }
926: if ($toperm && $permemail) {
927: if ($notify && $numnotify) {
928: if (grep(/^\Q$permemail\E/,split(/,/,$notify))) {
929: $numperm = 1;
930: }
931: }
932: unless ($numperm) {
933: $numperm = &sendnotification($permemail,$user,$domain,$subject,0,
934: $text,$msgid);
935: }
936: }
937: if ($toperm) {
938: $permlogmsgstatus = '. Perm. email log status '.
939: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
940: "Perm. e-mail count $numperm for $user at $domain");
941: if (ref($permresults) eq 'HASH') {
942: $permresults->{"$user:$domain"} = $numperm;
943: }
944: }
945: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
946: $env{'user.home'},
947: 'Sending '.$msgid.' to '.$user.' at '.$domain.' with status '.$status.
948: $permlogmsgstatus);
949: } else {
950: $status='no_host';
951: }
952: return $status;
953: }
954:
955: sub user_normal_msg {
956: my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
957: $toperm,$sentmessage,$symb,$restitle,$error,$nosentstore,$recipid,
958: $permresults,$senthide)=@_;
959: my @status;
960: my %userenv = &Apache::lonnet::get('environment',['msgforward'],
961: $domain,$user);
962: my $msgforward=$userenv{'msgforward'};
963: if ($msgforward) {
964: foreach my $fwd (split(/\,/,$msgforward)) {
965: my ($forwuser,$forwdomain)=split(/\:/,$fwd);
966: push(@status,
967: &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
968: $citation,$baseurl,$attachmenturl,$toperm,
969: undef,undef,$sentmessage,undef,$symb,
970: $restitle,$error,$nosentstore,$recipid,
971: $permresults,$senthide));
972: }
973: } else {
974: push(@status,&user_normal_msg_raw($user,$domain,$subject,$message,
975: $citation,$baseurl,$attachmenturl,$toperm,
976: undef,undef,$sentmessage,undef,$symb,
977: $restitle,$error,$nosentstore,$recipid,
978: $permresults,$senthide));
979: }
980: if (wantarray) {
981: return @status;
982: }
983: return join(' ',@status);
984: }
985:
986: sub process_sent_mail {
987: my ($msgsubj,$subj_prefix,$numsent,$stamp,$msgname,$msgdom,$msgcount,
988: $context,$pid,$savemsg,$recusers,$recudoms,$baseurl,$attachmenturl,
989: $symb,$error,$senderuname,$senderdom,$recipid) = @_;
990: my $sentsubj;
991: if ($numsent > 1) {
992: $sentsubj = $subj_prefix.' ('.$numsent.' sent) '.$msgsubj;
993: } else {
994: if ($subj_prefix) {
995: $sentsubj = $subj_prefix.' ';
996: }
997: $sentsubj .= $msgsubj;
998: }
999: $sentsubj = &HTML::Entities::encode($sentsubj,'<>&"');
1000: my $sentmsgid =
1001: &buildmsgid($stamp,$sentsubj,$msgname,$msgdom,$msgcount,$context,$pid);
1002: (undef,my $sentmessage) =
1003: &packagemsg($msgsubj,$savemsg,undef,$baseurl,$attachmenturl,$recusers,
1004: $recudoms,$sentmsgid,undef,undef,$symb,$error,$recipid);
1005: my $status = &store_sent_mail($sentmsgid,$sentmessage,$senderuname,
1006: $senderdom);
1007: return $status;
1008: }
1009:
1010: sub store_sent_mail {
1011: my ($msgid,$message,$senderuname,$senderdom) = @_;
1012: if ($senderuname eq '') {
1013: $senderuname = $env{'user.name'};
1014: }
1015: if ($senderdom eq '') {
1016: $senderdom = $env{'user.domain'};
1017: }
1018: my $status =' '.&Apache::lonnet::cput('nohist_email_sent',
1019: {$msgid => $message},
1020: $senderdom,$senderuname);
1021: return $status;
1022: }
1023:
1024: sub store_recipients {
1025: my ($subject,$sendername,$senderdom,$reciphash) = @_;
1026: my $context = &get_course_context();
1027: my $now = time();
1028: my $msgcount = &get_uniq();
1029: my $recipid =
1030: &buildmsgid($now,$subject,$sendername,$senderdom,$msgcount,$context,$$);
1031: my %recipinfo = (
1032: $recipid => $reciphash,
1033: );
1034: my $status = &Apache::lonnet::put('nohist_emailrecip',\%recipinfo,
1035: $senderdom,$sendername);
1036: if ($status eq 'ok') {
1037: return ($recipid,$status);
1038: } else {
1039: return (undef,$status);
1040: }
1041: }
1042:
1043:
1044: sub foldersuffix {
1045: my $folder=shift;
1046: unless ($folder) { return ''; }
1047: my $suffix;
1048: my %folderhash = &get_user_folders($folder);
1049: if (ref($folderhash{$folder}) eq 'HASH') {
1050: $suffix = '_'.&escape($folderhash{$folder}{'id'});
1051: } else {
1052: $suffix = '_'.&escape($folder);
1053: }
1054: return $suffix;
1055: }
1056:
1057:
1058: sub get_user_folders {
1059: my ($folder) = @_;
1060: my %userfolders =
1061: &Apache::lonnet::dump('email_folders',undef,undef,$folder);
1062: my $lock = "\0".'lock_counter'; # locks db while counter incremented
1063: my $counter = "\0".'idcount'; # used in suffix for email db files
1064: if (defined($userfolders{$lock})) {
1065: delete($userfolders{$lock});
1066: }
1067: if (defined($userfolders{$counter})) {
1068: delete($userfolders{$counter});
1069: }
1070: return %userfolders;
1071: }
1072:
1073: sub secapply {
1074: my $rec=shift;
1075: my $defaultflag=shift;
1076: $rec=~s/\s+//g;
1077: unless ($rec =~ /\:/) {
1078: $rec=~s/\@/\:/g;
1079: }
1080: my ($adr,$sections_or_groups)=($rec=~/^([^\(]+)\(([^\)]+)\)/);
1081: if ($sections_or_groups) {
1082: foreach my $item (split(/\;/,$sections_or_groups)) {
1083: if (($item eq $env{'request.course.sec'}) ||
1084: ($defaultflag && ($item eq '*'))) {
1085: return $adr;
1086: } elsif ($env{'request.course.groups'}) {
1087: my @usersgroups = split(/:/,$env{'request.course.groups'});
1088: if (grep(/^\Q$item\E$/,@usersgroups)) {
1089: return $adr;
1090: }
1091: }
1092: }
1093: } else {
1094: return $rec;
1095: }
1096: return '';
1097: }
1098:
1099: sub decide_receiver {
1100: my ($feedurl,$author,$question,$course,$policy,$defaultflag) = @_;
1101: &Apache::lonenc::check_decrypt(\$feedurl);
1102: my $typestyle='';
1103: my %to=();
1104: if ($env{'form.discuss'} eq 'author' ||$author) {
1105: $typestyle.='Submitting as Author Feedback<br />';
1106: $feedurl=~ m{^/res/($LONCAPA::domain_re)/($LONCAPA::username_re)/};
1107: $to{$2.':'.$1}=1;
1108: }
1109: my $cid = $env{'request.course.id'};
1110: if ($env{'form.discuss'} eq 'question' ||$question) {
1111: $typestyle.=&mt('Submitting as Question').'<br />';
1112: foreach my $item (split(/\,/,$env{'course.'.$cid.'.question.email'})) {
1113: my $rec=&secapply($item,$defaultflag);
1114: if ($rec) { $to{$rec}=1; }
1115: }
1116: }
1117: if ($env{'form.discuss'} eq 'course' ||$course) {
1118: $typestyle.=&mt('Submitting as Comment').'<br />';
1119: foreach my $item (split(/\,/,$env{'course.'.$cid.'.comment.email'})) {
1120: my $rec=&secapply($item,$defaultflag);
1121: if ($rec) { $to{$rec}=1; }
1122: }
1123: }
1124: if ($env{'form.discuss'} eq 'policy' ||$policy) {
1125: $typestyle.=&mt('Submitting as Policy Feedback').'<br />';
1126: foreach my $item (split(/\,/,$env{'course.'.$cid.'.policy.email'})) {
1127: my $rec=&secapply($item,$defaultflag);
1128: if ($rec) { $to{$rec}=1; }
1129: }
1130: }
1131: if ((scalar(%to) eq '0') && (!$defaultflag)) {
1132: ($typestyle,%to)=
1133: &decide_receiver($feedurl,$author,$question,$course,$policy,1);
1134: }
1135: return ($typestyle,%to);
1136: }
1137:
1138: 1;
1139: __END__
1140:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>