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