1: # The LearningOnline Network with CAPA
2: # Routines for messaging
3: #
4: # $Id: lonmsg.pm,v 1.186 2006/11/01 22:22:31 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: my %senderemails=&Apache::loncommon::getemails();
214: my $senderaddress='';
215: foreach my $type ('notification','permanentemail','critnotification') {
216: if ($senderemails{$type}) {
217: $senderaddress=$senderemails{$type};
218: }
219: }
220: $body=
221: "*** ".&mt('This is an automatic message generated by the LON-CAPA system.')."\n".
222: "*** ".($senderaddress?&mt('You can reply to this message'):&mt('Please do not reply to this address.')."\n*** ".
223: &mt('A reply will not be received by the recipient!'))."\n\n".$body;
224: my $msg = new Mail::Send;
225: $msg->to($to);
226: $msg->subject('[LON-CAPA] '.$subject);
227: if ($senderaddress) { $msg->add('Reply-to',$senderaddress); }
228: if (my $fh = $msg->open()) {
229: print $fh $body;
230: $fh->close;
231: }
232: }
233:
234: # ==================================================== Send notification emails
235:
236: sub sendnotification {
237: my ($to,$touname,$toudom,$subj,$crit,$text)=@_;
238: my $sender=$env{'environment.firstname'}.' '.$env{'environment.lastname'};
239: unless ($sender=~/\w/) {
240: $sender=$env{'user.name'}.'@'.$env{'user.domain'};
241: }
242: my $critical=($crit?' critical':'');
243: $text=~s/\<\;/\</gs;
244: $text=~s/\>\;/\>/gs;
245: $text=~s/\<\/*[^\>]+\>//gs;
246: my $url='http://'.
247: $Apache::lonnet::hostname{&Apache::lonnet::homeserver($touname,$toudom)}.
248: '/adm/email?username='.$touname.'&domain='.$toudom;
249: my $body=(<<ENDMSG);
250: You received a$critical message from $sender in LON-CAPA. The subject is
251:
252: $subj
253:
254: === Excerpt ============================================================
255: $text
256: ========================================================================
257:
258: Use
259:
260: $url
261:
262: to access the full message.
263: ENDMSG
264: &sendemail($to,'New'.$critical.' message from '.$sender,$body);
265: }
266: # ============================================================= Check for email
267:
268: sub newmail {
269: if ((time-$env{'user.mailcheck.time'})>300) {
270: my %what=&Apache::lonnet::get('email_status',['recnewemail']);
271: &Apache::lonnet::appenv('user.mailcheck.time'=>time);
272: if ($what{'recnewemail'}>0) { return 1; }
273: }
274: return 0;
275: }
276:
277: # =============================== Automated message to the author of a resource
278:
279: =pod
280:
281: =item * B<author_res_msg($filename, $message)>: Sends message $message to the owner
282: of the resource with the URI $filename.
283:
284: =cut
285:
286: sub author_res_msg {
287: my ($filename,$message)=@_;
288: unless ($message) { return 'empty'; }
289: $filename=&Apache::lonnet::declutter($filename);
290: my ($domain,$author,@dummy)=split(/\//,$filename);
291: my $homeserver=&Apache::lonnet::homeserver($author,$domain);
292: if ($homeserver ne 'no_host') {
293: my $id=unpack("%32C*",$message);
294: $message .= " <p>This error occurred on machine ".
295: $Apache::lonnet::perlvar{'lonHostID'}."</p>";
296: my $msgid;
297: ($msgid,$message)=&packagemsg($filename,$message);
298: return &Apache::lonnet::reply('put:'.$domain.':'.$author.
299: ':nohist_res_msgs:'.
300: &escape($filename.'_'.$id).'='.
301: &escape($message),$homeserver);
302: }
303: return 'no_host';
304: }
305:
306: # =========================================== Retrieve author resource messages
307:
308: sub retrieve_author_res_msg {
309: my $url=shift;
310: $url=&Apache::lonnet::declutter($url);
311: my ($domain,$author)=($url=~/^(\w+)\/(\w+)\//);
312: my %errormsgs=&Apache::lonnet::dump('nohist_res_msgs',$domain,$author);
313: my $msgs='';
314: foreach (keys %errormsgs) {
315: if ($_=~/^\Q$url\E\_\d+$/) {
316: my %content=&unpackagemsg($errormsgs{$_});
317: $msgs.='<p><img src="/adm/lonMisc/bomb.gif" /><b>'.
318: $content{'time'}.'</b>: '.$content{'message'}.
319: '<br /></p>';
320: }
321: }
322: return $msgs;
323: }
324:
325:
326: # =============================== Delete all author messages related to one URL
327:
328: sub del_url_author_res_msg {
329: my $url=shift;
330: $url=&Apache::lonnet::declutter($url);
331: my ($domain,$author)=($url=~/^(\w+)\/(\w+)\//);
332: my @delmsgs=();
333: foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
334: if ($_=~/^\Q$url\E\_\d+$/) {
335: push (@delmsgs,$_);
336: }
337: }
338: return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
339: }
340: # =================================== Clear out all author messages in URL path
341:
342: sub clear_author_res_msg {
343: my $url=shift;
344: $url=&Apache::lonnet::declutter($url);
345: my ($domain,$author)=($url=~/^(\w+)\/(\w+)\//);
346: my @delmsgs=();
347: foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
348: if ($_=~/^\Q$url\E/) {
349: push (@delmsgs,$_);
350: }
351: }
352: return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
353: }
354: # ================= Return hash with URLs for which there is a resource message
355:
356: sub all_url_author_res_msg {
357: my ($author,$domain)=@_;
358: my %returnhash=();
359: foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
360: $_=~/^(.+)\_\d+/;
361: $returnhash{$1}=1;
362: }
363: return %returnhash;
364: }
365:
366: # ====================================== Add a comment to the User Notes screen
367:
368: sub store_instructor_comment {
369: my ($msg,$uname,$udom) = @_;
370: my $cid = $env{'request.course.id'};
371: my $cnum = $env{'course.'.$cid.'.num'};
372: my $cdom = $env{'course.'.$cid.'.domain'};
373: my $subject= &mt('Record').' ['.$uname.':'.$udom.']';
374: my $result = &user_normal_msg_raw($cnum,$cdom,$subject,$msg);
375: return $result;
376: }
377:
378: # ================================================== Critical message to a user
379:
380: sub user_crit_msg_raw {
381: my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage)=@_;
382: # Check if allowed missing
383: my $status='';
384: my $msgid='undefined';
385: unless (($message)&&($user)&&($domain)) { $status='empty'; };
386: my $text=$message;
387: my $homeserver=&Apache::lonnet::homeserver($user,$domain);
388: if ($homeserver ne 'no_host') {
389: ($msgid,$message)=&packagemsg($subject,$message);
390: if ($sendback) { $message.='<sendback>true</sendback>'; }
391: $status=&Apache::lonnet::critical(
392: 'put:'.$domain.':'.$user.':critical:'.
393: &escape($msgid).'='.
394: &escape($message),$homeserver);
395: if (defined($sentmessage)) {
396: $$sentmessage = $message;
397: }
398: } else {
399: $status='no_host';
400: }
401: # Notifications
402: my %userenv = &Apache::loncommon::getemails($user,$domain);
403: if ($userenv{'critnotification'}) {
404: &sendnotification($userenv{'critnotification'},$user,$domain,$subject,1,
405: $text);
406: }
407: if ($toperm && $userenv{'permanentemail'}) {
408: &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,1,
409: $text);
410: }
411: # Log this
412: &Apache::lonnet::logthis(
413: 'Sending critical email '.$msgid.
414: ', log status: '.
415: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
416: $env{'user.home'},
417: 'Sending critical '.$msgid.' to '.$user.' at '.$domain.' with status: '
418: .$status));
419: return $status;
420: }
421:
422: # New routine that respects "forward" and calls old routine
423:
424: =pod
425:
426: =item * B<user_crit_msg($user, $domain, $subject, $message, $sendback)>: Sends
427: a critical message $message to the $user at $domain. If $sendback is true,
428: a reciept will be sent to the current user when $user recieves the message.
429:
430: Additionally it will check if the user has a Forwarding address
431: set, and send the message to that address instead
432:
433: returns
434: - in array context a list of results for each message that was sent
435: - in scalar context a space seperated list of results for each
436: message sent
437:
438: =cut
439:
440: sub user_crit_msg {
441: my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage)=@_;
442: my @status;
443: my %userenv = &Apache::lonnet::get('environment',['msgforward'],
444: $domain,$user);
445: my $msgforward=$userenv{'msgforward'};
446: if ($msgforward) {
447: foreach my $addr (split(/\,/,$msgforward)) {
448: my ($forwuser,$forwdomain)=split(/\:/,$addr);
449: push(@status,
450: &user_crit_msg_raw($forwuser,$forwdomain,$subject,$message,
451: $sendback,$toperm,$sentmessage));
452: }
453: } else {
454: push(@status,
455: &user_crit_msg_raw($user,$domain,$subject,$message,$sendback,
456: $toperm,$sentmessage));
457: }
458: if (wantarray) {
459: return @status;
460: }
461: return join(' ',@status);
462: }
463:
464: # =================================================== Critical message received
465:
466: sub user_crit_received {
467: my $msgid=shift;
468: my %message=&Apache::lonnet::get('critical',[$msgid]);
469: my %contents=&unpackagemsg($message{$msgid},1);
470: my $status='rec: '.($contents{'sendback'}?
471: &user_normal_msg($contents{'sendername'},$contents{'senderdomain'},
472: &mt('Receipt').': '.$env{'user.name'}.' '.&mt('at').' '.$env{'user.domain'}.', '.$contents{'subject'},
473: &mt('User').' '.$env{'user.name'}.' '.&mt('at').' '.$env{'user.domain'}.
474: ' acknowledged receipt of message'."\n".' "'.
475: $contents{'subject'}.'"'."\n".&mt('dated').' '.
476: $contents{'time'}.".\n"
477: ):'no msg req');
478: $status.=' trans: '.
479: &Apache::lonnet::put(
480: 'nohist_email',{$contents{'msgid'} => $message{$msgid}});
481: $status.=' del: '.
482: &Apache::lonnet::del('critical',[$contents{'msgid'}]);
483: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
484: $env{'user.home'},'Received critical message '.
485: $contents{'msgid'}.
486: ', '.$status);
487: return $status;
488: }
489:
490: # ======================================================== Normal communication
491:
492: sub user_normal_msg_raw {
493: my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
494: $toperm,$currid,$newid,$sentmessage,$crsmsgid)=@_;
495: # Check if allowed missing
496: my ($status,$packed_message);
497: my $msgid='undefined';
498: my $text=$message;
499: unless (($message)&&($user)&&($domain)) { $status='empty'; };
500: my $homeserver=&Apache::lonnet::homeserver($user,$domain);
501: if ($homeserver ne 'no_host') {
502: ($msgid,$packed_message)=
503: &packagemsg($subject,$message,$citation,$baseurl,
504: $attachmenturl,$user,$domain,$currid,
505: undef,$crsmsgid);
506:
507: # Store in user folder
508: $status=&Apache::lonnet::critical(
509: 'put:'.$domain.':'.$user.':nohist_email:'.
510: &escape($msgid).'='.
511: &escape($packed_message),$homeserver);
512: # Save new message received time
513: &Apache::lonnet::put
514: ('email_status',{'recnewemail'=>time},$domain,$user);
515: # Into sent-mail folder unless a broadcast message or critical message
516: unless (($env{'request.course.id'}) &&
517: (($env{'form.sendmode'} eq 'group') ||
518: (($env{'form.critmsg'}) || ($env{'form.sendbck'})) &&
519: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
520: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
521: '/'.$env{'request.course.sec'})))) {
522: (undef, my $packed_message_no_citation)=
523: &packagemsg($subject,$message,undef ,$baseurl,
524: $attachmenturl,$user,$domain,$currid,
525: undef,$crsmsgid);
526:
527: $status .= &store_sent_mail($msgid,$packed_message_no_citation);
528: }
529: } else {
530: $status='no_host';
531: }
532: if (defined($newid)) {
533: $$newid = $msgid;
534: }
535: if (defined($sentmessage)) {
536: $$sentmessage = $packed_message;
537: }
538:
539: # Notifications
540: my %userenv = &Apache::lonnet::get('environment',['notification',
541: 'permanentemail'],
542: $domain,$user);
543: if ($userenv{'notification'}) {
544: &sendnotification($userenv{'notification'},$user,$domain,$subject,0,
545: $text);
546: }
547: if ($toperm && $userenv{'permanentemail'}) {
548: &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,0,
549: $text);
550: }
551: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
552: $env{'user.home'},
553: 'Sending '.$msgid.' to '.$user.' at '.$domain.' with status: '.$status);
554: return $status;
555: }
556:
557: # New routine that respects "forward" and calls old routine
558:
559: =pod
560:
561: =item * B<user_normal_msg($user, $domain, $subject, $message,
562: $citation, $baseurl, $attachmenturl)>: Sends a message to the
563: $user at $domain, with subject $subject and message $message.
564:
565: =cut
566:
567: sub user_normal_msg {
568: my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
569: $toperm,$sentmessage)=@_;
570: my $status='';
571: my %userenv = &Apache::lonnet::get('environment',['msgforward'],
572: $domain,$user);
573: my $msgforward=$userenv{'msgforward'};
574: if ($msgforward) {
575: foreach (split(/\,/,$msgforward)) {
576: my ($forwuser,$forwdomain)=split(/\:/,$_);
577: $status.=
578: &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
579: $citation,$baseurl,$attachmenturl,$toperm,
580: undef,undef,$sentmessage).' ';
581: }
582: } else {
583: $status=&user_normal_msg_raw($user,$domain,$subject,$message,
584: $citation,$baseurl,$attachmenturl,$toperm,
585: undef,undef,$sentmessage);
586: }
587: return $status;
588: }
589:
590: sub store_sent_mail {
591: my ($msgid,$message) = @_;
592: my $status =' '.&Apache::lonnet::critical(
593: 'put:'.$env{'user.domain'}.':'.$env{'user.name'}.
594: ':nohist_email_sent:'.
595: &escape($msgid).'='.
596: &escape($message),$env{'user.home'});
597: return $status;
598: }
599:
600: # =============================================================== Folder suffix
601:
602: sub foldersuffix {
603: my $folder=shift;
604: unless ($folder) { return ''; }
605: return '_'.&escape($folder);
606: }
607:
608: 1;
609: __END__
610:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>