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