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