1: # The LearningOnline Network with CAPA
2: # Routines for messaging
3: #
4: # $Id: lonmsg.pm,v 1.184 2006/05/30 12:46:09 www 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: use strict;
32: use Apache::lonnet;
33: use HTML::TokeParser();
34: use Apache::lonlocal;
35: use Mail::Send;
36: use lib '/home/httpd/lib/perl/';
37: use LONCAPA;
38:
39: {
40: my $uniq;
41: sub get_uniq {
42: $uniq++;
43: return $uniq;
44: }
45: }
46:
47: # ===================================================================== Package
48:
49: sub packagemsg {
50: my ($subject,$message,$citation,$baseurl,$attachmenturl,
51: $recuser,$recdomain,$msgid,$type,$crsmsgid)=@_;
52: $message =&HTML::Entities::encode($message,'<>&"');
53: $citation=&HTML::Entities::encode($citation,'<>&"');
54: $subject =&HTML::Entities::encode($subject,'<>&"');
55: #remove machine specification
56: $baseurl =~ s|^http://[^/]+/|/|;
57: $baseurl =&HTML::Entities::encode($baseurl,'<>&"');
58: #remove machine specification
59: $attachmenturl =~ s|^http://[^/]+/|/|;
60: $attachmenturl =&HTML::Entities::encode($attachmenturl,'<>&"');
61: my $course_context;
62: if (defined($env{'form.replyid'})) {
63: my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid)=
64: split(/\:/,&unescape($env{'form.replyid'}));
65: $course_context = $origcid;
66: }
67: foreach my $key (keys(%env)) {
68: if ($key=~/^form\.(rep)?rec\_(.*)$/) {
69: my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid) =
70: split(/\:/,&unescape($2));
71: $course_context = $origcid;
72: last;
73: }
74: }
75: unless(defined($course_context)) {
76: $course_context = $env{'request.course.id'};
77: }
78: my $now=time;
79: my $msgcount = &get_uniq();
80: unless(defined($msgid)) {
81: $msgid = &buildmsgid($now,$subject,$env{'user.name'},$env{'user.domain'},
82: $msgcount,$course_context,$$);
83: }
84: my $result = '<sendername>'.$env{'user.name'}.'</sendername>'.
85: '<senderdomain>'.$env{'user.domain'}.'</senderdomain>'.
86: '<subject>'.$subject.'</subject>'.
87: '<time>'.&Apache::lonlocal::locallocaltime($now).'</time>';
88: if (defined($crsmsgid)) {
89: $result.= '<courseid>'.$course_context.'</courseid>'.
90: '<coursesec>'.$env{'request.course.sec'}.'</coursesec>'.
91: '<msgid>'.$msgid.'</msgid>'.
92: '<coursemsgid>'.$crsmsgid.'</coursemsgid>'.
93: '<message>'.$message.'</message>';
94: return ($msgid,$result);
95: }
96: $result .= '<servername>'.$ENV{'SERVER_NAME'}.'</servername>'.
97: '<host>'.$ENV{'HTTP_HOST'}.'</host>'.
98: '<client>'.$ENV{'REMOTE_ADDR'}.'</client>'.
99: '<browsertype>'.$env{'browser.type'}.'</browsertype>'.
100: '<browseros>'.$env{'browser.os'}.'</browseros>'.
101: '<browserversion>'.$env{'browser.version'}.'</browserversion>'.
102: '<browsermathml>'.$env{'browser.mathml'}.'</browsermathml>'.
103: '<browserraw>'.$ENV{'HTTP_USER_AGENT'}.'</browserraw>'.
104: '<courseid>'.$course_context.'</courseid>'.
105: '<coursesec>'.$env{'request.course.sec'}.'</coursesec>'.
106: '<role>'.$env{'request.role'}.'</role>'.
107: '<resource>'.$env{'request.filename'}.'</resource>'.
108: '<msgid>'.$msgid.'</msgid>';
109: if (ref($recuser) eq 'ARRAY') {
110: for (my $i=0; $i<@{$recuser}; $i++) {
111: if ($type eq 'dcmail') {
112: my ($username,$email) = split(/:/,$$recuser[$i]);
113: $username = &unescape($username);
114: $email = &unescape($email);
115: $username = &HTML::Entities::encode($username,'<>&"');
116: $email = &HTML::Entities::encode($email,'<>&"');
117: $result .= '<recipient username="'.$username.'">'.
118: $email.'</recipient>';
119: } else {
120: $result .= '<recuser>'.$$recuser[$i].'</recuser>'.
121: '<recdomain>'.$$recdomain[$i].'</recdomain>';
122: }
123: }
124: } else {
125: $result .= '<recuser>'.$recuser.'</recuser>'.
126: '<recdomain>'.$recdomain.'</recdomain>';
127: }
128: $result .= '<message>'.$message.'</message>';
129: if (defined($citation)) {
130: $result.='<citation>'.$citation.'</citation>';
131: }
132: if (defined($baseurl)) {
133: $result.= '<baseurl>'.$baseurl.'</baseurl>';
134: }
135: if (defined($attachmenturl)) {
136: $result.= '<attachmenturl>'.$attachmenturl.'</attachmenturl>';
137: }
138: return $msgid,$result;
139: }
140:
141: # ================================================== Unpack message into a hash
142:
143: sub unpackagemsg {
144: my ($message,$notoken)=@_;
145: my %content=();
146: my $parser=HTML::TokeParser->new(\$message);
147: my $token;
148: while ($token=$parser->get_token) {
149: if ($token->[0] eq 'S') {
150: my $entry=$token->[1];
151: my $value=$parser->get_text('/'.$entry);
152: if (($entry eq 'recuser') || ($entry eq 'recdomain')) {
153: push(@{$content{$entry}},$value);
154: } elsif ($entry eq 'recipient') {
155: my $username = $token->[2]{'username'};
156: $username = &HTML::Entities::decode($username,'<>&"');
157: $content{$entry}{$username} = $value;
158: } else {
159: $content{$entry}=$value;
160: }
161: }
162: }
163: if (!exists($content{'recuser'})) { $content{'recuser'} = []; }
164: if ($content{'attachmenturl'}) {
165: my ($fname)=($content{'attachmenturl'}=~m|/([^/]+)$|);
166: if ($notoken) {
167: $content{'message'}.='<p>'.&mt('Attachment').': <tt>'.$fname.'</tt>';
168: } else {
169: &Apache::lonnet::allowuploaded('/adm/msg',
170: $content{'attachmenturl'});
171: $content{'message'}.='<p>'.&mt('Attachment').
172: ': <a href="'.$content{'attachmenturl'}.'"><tt>'.
173: $fname.'</tt></a>';
174: }
175: }
176: return %content;
177: }
178:
179: # ======================================================= Get info out of msgid
180:
181: sub buildmsgid {
182: my ($now,$subject,$uname,$udom,$msgcount,$course_context,$pid) = @_;
183: $subject=&escape($subject);
184: return(&escape($now.':'.$subject.':'.$uname.':'.
185: $udom.':'.$msgcount.':'.$course_context.':'.$pid));
186: }
187:
188: sub unpackmsgid {
189: my ($msgid,$folder,$skipstatus,$status_cache)=@_;
190: $msgid=&unescape($msgid);
191: my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$fromcid,
192: $processid)=split(/\:/,&unescape($msgid));
193: $shortsubj = &unescape($shortsubj);
194: $shortsubj = &HTML::Entities::decode($shortsubj);
195: if (!defined($processid)) { $fromcid = ''; }
196: my %status=();
197: unless ($skipstatus) {
198: if (ref($status_cache)) {
199: $status{$msgid} = $status_cache->{$msgid};
200: } else {
201: my $suffix=&foldersuffix($folder);
202: %status=&Apache::lonnet::get('email_status'.$suffix,[$msgid]);
203: }
204: if ($status{$msgid}=~/^error\:/) { $status{$msgid}=''; }
205: unless ($status{$msgid}) { $status{$msgid}='new'; }
206: }
207: return ($sendtime,$shortsubj,$fromname,$fromdomain,$status{$msgid},$fromcid);
208: }
209:
210:
211: sub sendemail {
212: my ($to,$subject,$body)=@_;
213: $body=
214: "*** ".&mt('This is an automatic message generated by the LON-CAPA system.')."\n".
215: "*** ".&mt('Please do not reply to this address.')."\n\n".$body;
216: my $msg = new Mail::Send;
217: $msg->to($to);
218: $msg->subject('[LON-CAPA] '.$subject);
219: if (my $fh = $msg->open()) {
220: print $fh $body;
221: $fh->close;
222: }
223: }
224:
225: # ==================================================== Send notification emails
226:
227: sub sendnotification {
228: my ($to,$touname,$toudom,$subj,$crit,$text)=@_;
229: my $sender=$env{'environment.firstname'}.' '.$env{'environment.lastname'};
230: unless ($sender=~/\w/) {
231: $sender=$env{'user.name'}.'@'.$env{'user.domain'};
232: }
233: my $critical=($crit?' critical':'');
234: $text=~s/\<\;/\</gs;
235: $text=~s/\>\;/\>/gs;
236: $text=~s/\<\/*[^\>]+\>//gs;
237: my $url='http://'.
238: $Apache::lonnet::hostname{&Apache::lonnet::homeserver($touname,$toudom)}.
239: '/adm/email?username='.$touname.'&domain='.$toudom;
240: my $body=(<<ENDMSG);
241: You received a$critical message from $sender in LON-CAPA. The subject is
242:
243: $subj
244:
245: === Excerpt ============================================================
246: $text
247: ========================================================================
248:
249: Use
250:
251: $url
252:
253: to access the full message.
254: ENDMSG
255: &sendemail($to,'New'.$critical.' message from '.$sender,$body);
256: }
257: # ============================================================= Check for email
258:
259: sub newmail {
260: if ((time-$env{'user.mailcheck.time'})>300) {
261: my %what=&Apache::lonnet::get('email_status',['recnewemail']);
262: &Apache::lonnet::appenv('user.mailcheck.time'=>time);
263: if ($what{'recnewemail'}>0) { return 1; }
264: }
265: return 0;
266: }
267:
268: # =============================== Automated message to the author of a resource
269:
270: =pod
271:
272: =item * B<author_res_msg($filename, $message)>: Sends message $message to the owner
273: of the resource with the URI $filename.
274:
275: =cut
276:
277: sub author_res_msg {
278: my ($filename,$message)=@_;
279: unless ($message) { return 'empty'; }
280: $filename=&Apache::lonnet::declutter($filename);
281: my ($domain,$author,@dummy)=split(/\//,$filename);
282: my $homeserver=&Apache::lonnet::homeserver($author,$domain);
283: if ($homeserver ne 'no_host') {
284: my $id=unpack("%32C*",$message);
285: $message .= " <p>This error occurred on machine ".
286: $Apache::lonnet::perlvar{'lonHostID'}."</p>";
287: my $msgid;
288: ($msgid,$message)=&packagemsg($filename,$message);
289: return &Apache::lonnet::reply('put:'.$domain.':'.$author.
290: ':nohist_res_msgs:'.
291: &escape($filename.'_'.$id).'='.
292: &escape($message),$homeserver);
293: }
294: return 'no_host';
295: }
296:
297: # =========================================== Retrieve author resource messages
298:
299: sub retrieve_author_res_msg {
300: my $url=shift;
301: $url=&Apache::lonnet::declutter($url);
302: my ($domain,$author)=($url=~/^(\w+)\/(\w+)\//);
303: my %errormsgs=&Apache::lonnet::dump('nohist_res_msgs',$domain,$author);
304: my $msgs='';
305: foreach (keys %errormsgs) {
306: if ($_=~/^\Q$url\E\_\d+$/) {
307: my %content=&unpackagemsg($errormsgs{$_});
308: $msgs.='<p><img src="/adm/lonMisc/bomb.gif" /><b>'.
309: $content{'time'}.'</b>: '.$content{'message'}.
310: '<br /></p>';
311: }
312: }
313: return $msgs;
314: }
315:
316:
317: # =============================== Delete all author messages related to one URL
318:
319: sub del_url_author_res_msg {
320: my $url=shift;
321: $url=&Apache::lonnet::declutter($url);
322: my ($domain,$author)=($url=~/^(\w+)\/(\w+)\//);
323: my @delmsgs=();
324: foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
325: if ($_=~/^\Q$url\E\_\d+$/) {
326: push (@delmsgs,$_);
327: }
328: }
329: return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
330: }
331: # =================================== Clear out all author messages in URL path
332:
333: sub clear_author_res_msg {
334: my $url=shift;
335: $url=&Apache::lonnet::declutter($url);
336: my ($domain,$author)=($url=~/^(\w+)\/(\w+)\//);
337: my @delmsgs=();
338: foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
339: if ($_=~/^\Q$url\E/) {
340: push (@delmsgs,$_);
341: }
342: }
343: return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
344: }
345: # ================= Return hash with URLs for which there is a resource message
346:
347: sub all_url_author_res_msg {
348: my ($author,$domain)=@_;
349: my %returnhash=();
350: foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
351: $_=~/^(.+)\_\d+/;
352: $returnhash{$1}=1;
353: }
354: return %returnhash;
355: }
356:
357: # ================================================== Critical message to a user
358:
359: sub user_crit_msg_raw {
360: my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage)=@_;
361: # Check if allowed missing
362: my $status='';
363: my $msgid='undefined';
364: unless (($message)&&($user)&&($domain)) { $status='empty'; };
365: my $text=$message;
366: my $homeserver=&Apache::lonnet::homeserver($user,$domain);
367: if ($homeserver ne 'no_host') {
368: ($msgid,$message)=&packagemsg($subject,$message);
369: if ($sendback) { $message.='<sendback>true</sendback>'; }
370: $status=&Apache::lonnet::critical(
371: 'put:'.$domain.':'.$user.':critical:'.
372: &escape($msgid).'='.
373: &escape($message),$homeserver);
374: if (defined($sentmessage)) {
375: $$sentmessage = $message;
376: }
377: } else {
378: $status='no_host';
379: }
380: # Notifications
381: my %userenv = &Apache::lonnet::get('environment',['critnotification',
382: 'permanentemail'],
383: $domain,$user);
384: if ($userenv{'critnotification'}) {
385: &sendnotification($userenv{'critnotification'},$user,$domain,$subject,1,
386: $text);
387: }
388: if ($toperm && $userenv{'permanentemail'}) {
389: &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,1,
390: $text);
391: }
392: # Log this
393: &Apache::lonnet::logthis(
394: 'Sending critical email '.$msgid.
395: ', log status: '.
396: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
397: $env{'user.home'},
398: 'Sending critical '.$msgid.' to '.$user.' at '.$domain.' with status: '
399: .$status));
400: return $status;
401: }
402:
403: # New routine that respects "forward" and calls old routine
404:
405: =pod
406:
407: =item * B<user_crit_msg($user, $domain, $subject, $message, $sendback)>: Sends
408: a critical message $message to the $user at $domain. If $sendback is true,
409: a reciept will be sent to the current user when $user recieves the message.
410:
411: Additionally it will check if the user has a Forwarding address
412: set, and send the message to that address instead
413:
414: returns
415: - in array context a list of results for each message that was sent
416: - in scalar context a space seperated list of results for each
417: message sent
418:
419: =cut
420:
421: sub user_crit_msg {
422: my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage)=@_;
423: my @status;
424: my %userenv = &Apache::lonnet::get('environment',['msgforward'],
425: $domain,$user);
426: my $msgforward=$userenv{'msgforward'};
427: if ($msgforward) {
428: foreach my $addr (split(/\,/,$msgforward)) {
429: my ($forwuser,$forwdomain)=split(/\:/,$addr);
430: push(@status,
431: &user_crit_msg_raw($forwuser,$forwdomain,$subject,$message,
432: $sendback,$toperm,$sentmessage));
433: }
434: } else {
435: push(@status,
436: &user_crit_msg_raw($user,$domain,$subject,$message,$sendback,
437: $toperm,$sentmessage));
438: }
439: if (wantarray) {
440: return @status;
441: }
442: return join(' ',@status);
443: }
444:
445: # =================================================== Critical message received
446:
447: sub user_crit_received {
448: my $msgid=shift;
449: my %message=&Apache::lonnet::get('critical',[$msgid]);
450: my %contents=&unpackagemsg($message{$msgid},1);
451: my $status='rec: '.($contents{'sendback'}?
452: &user_normal_msg($contents{'sendername'},$contents{'senderdomain'},
453: &mt('Receipt').': '.$env{'user.name'}.' '.&mt('at').' '.$env{'user.domain'}.', '.$contents{'subject'},
454: &mt('User').' '.$env{'user.name'}.' '.&mt('at').' '.$env{'user.domain'}.
455: ' acknowledged receipt of message'."\n".' "'.
456: $contents{'subject'}.'"'."\n".&mt('dated').' '.
457: $contents{'time'}.".\n"
458: ):'no msg req');
459: $status.=' trans: '.
460: &Apache::lonnet::put(
461: 'nohist_email',{$contents{'msgid'} => $message{$msgid}});
462: $status.=' del: '.
463: &Apache::lonnet::del('critical',[$contents{'msgid'}]);
464: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
465: $env{'user.home'},'Received critical message '.
466: $contents{'msgid'}.
467: ', '.$status);
468: return $status;
469: }
470:
471: # ======================================================== Normal communication
472:
473: sub user_normal_msg_raw {
474: my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
475: $toperm,$currid,$newid,$sentmessage,$crsmsgid)=@_;
476: # Check if allowed missing
477: my ($status,$packed_message);
478: my $msgid='undefined';
479: my $text=$message;
480: unless (($message)&&($user)&&($domain)) { $status='empty'; };
481: my $homeserver=&Apache::lonnet::homeserver($user,$domain);
482: if ($homeserver ne 'no_host') {
483: ($msgid,$packed_message)=
484: &packagemsg($subject,$message,$citation,$baseurl,
485: $attachmenturl,$user,$domain,$currid,
486: undef,$crsmsgid);
487:
488: # Store in user folder
489: $status=&Apache::lonnet::critical(
490: 'put:'.$domain.':'.$user.':nohist_email:'.
491: &escape($msgid).'='.
492: &escape($packed_message),$homeserver);
493: # Save new message received time
494: &Apache::lonnet::put
495: ('email_status',{'recnewemail'=>time},$domain,$user);
496: # Into sent-mail folder unless a broadcast message or critical message
497: unless (($env{'request.course.id'}) &&
498: (($env{'form.sendmode'} eq 'group') ||
499: (($env{'form.critmsg'}) || ($env{'form.sendbck'})) &&
500: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
501: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
502: '/'.$env{'request.course.sec'})))) {
503: (undef, my $packed_message_no_citation)=
504: &packagemsg($subject,$message,undef ,$baseurl,
505: $attachmenturl,$user,$domain,$currid,
506: undef,$crsmsgid);
507:
508: $status .= &store_sent_mail($msgid,$packed_message_no_citation);
509: }
510: } else {
511: $status='no_host';
512: }
513: if (defined($newid)) {
514: $$newid = $msgid;
515: }
516: if (defined($sentmessage)) {
517: $$sentmessage = $packed_message;
518: }
519:
520: # Notifications
521: my %userenv = &Apache::lonnet::get('environment',['notification',
522: 'permanentemail'],
523: $domain,$user);
524: if ($userenv{'notification'}) {
525: &sendnotification($userenv{'notification'},$user,$domain,$subject,0,
526: $text);
527: }
528: if ($toperm && $userenv{'permanentemail'}) {
529: &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,0,
530: $text);
531: }
532: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
533: $env{'user.home'},
534: 'Sending '.$msgid.' to '.$user.' at '.$domain.' with status: '.$status);
535: return $status;
536: }
537:
538: # New routine that respects "forward" and calls old routine
539:
540: =pod
541:
542: =item * B<user_normal_msg($user, $domain, $subject, $message,
543: $citation, $baseurl, $attachmenturl)>: Sends a message to the
544: $user at $domain, with subject $subject and message $message.
545:
546: =cut
547:
548: sub user_normal_msg {
549: my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
550: $toperm,$sentmessage)=@_;
551: my $status='';
552: my %userenv = &Apache::lonnet::get('environment',['msgforward'],
553: $domain,$user);
554: my $msgforward=$userenv{'msgforward'};
555: if ($msgforward) {
556: foreach (split(/\,/,$msgforward)) {
557: my ($forwuser,$forwdomain)=split(/\:/,$_);
558: $status.=
559: &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
560: $citation,$baseurl,$attachmenturl,$toperm,
561: undef,undef,$sentmessage).' ';
562: }
563: } else {
564: $status=&user_normal_msg_raw($user,$domain,$subject,$message,
565: $citation,$baseurl,$attachmenturl,$toperm,
566: undef,undef,$sentmessage);
567: }
568: return $status;
569: }
570:
571: sub store_sent_mail {
572: my ($msgid,$message) = @_;
573: my $status =' '.&Apache::lonnet::critical(
574: 'put:'.$env{'user.domain'}.':'.$env{'user.name'}.
575: ':nohist_email_sent:'.
576: &escape($msgid).'='.
577: &escape($message),$env{'user.home'});
578: return $status;
579: }
580:
581: # =============================================================== Folder suffix
582:
583: sub foldersuffix {
584: my $folder=shift;
585: unless ($folder) { return ''; }
586: return '_'.&escape($folder);
587: }
588:
589: 1;
590: __END__
591:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>