[system] / trunk / webwork2 / lib / WeBWorK / ContentGenerator / Instructor / SendMail.pm Repository:
ViewVC logotype

Annotation of /trunk/webwork2/lib/WeBWorK/ContentGenerator/Instructor/SendMail.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2095 - (view) (download) (as text)

1 : sh002i 1663 ################################################################################
2 :     # WeBWorK Online Homework Delivery System
3 :     # Copyright © 2000-2003 The WeBWorK Project, http://openwebwork.sf.net/
4 : toenail 2095 # $CVSHeader: webwork-modperl/lib/WeBWorK/ContentGenerator/Instructor/SendMail.pm,v 1.30 2004/05/11 19:56:27 toenail Exp $
5 : sh002i 1663 #
6 :     # This program is free software; you can redistribute it and/or modify it under
7 :     # the terms of either: (a) the GNU General Public License as published by the
8 :     # Free Software Foundation; either version 2, or (at your option) any later
9 :     # version, or (b) the "Artistic License" which comes with this package.
10 :     #
11 :     # This program is distributed in the hope that it will be useful, but WITHOUT
12 :     # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 :     # FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the
14 :     # Artistic License for more details.
15 :     ################################################################################
16 :    
17 : gage 1368 package WeBWorK::ContentGenerator::Instructor::SendMail;
18 :     use base qw(WeBWorK::ContentGenerator::Instructor);
19 :    
20 :     =head1 NAME
21 :    
22 :     WeBWorK::ContentGenerator::Instructor::SendMail - Entry point for User-specific data editing
23 :    
24 :     =cut
25 :    
26 :     use strict;
27 :     use warnings;
28 :     use CGI qw();
29 : sh002i 1646 #use HTML::Entities;
30 : gage 1373 use Mail::Sender;
31 : gage 1368
32 : gage 2050 my $REFRESH_RESIZE_BUTTON = "Set preview to: "; # handle submit value idiocy
33 : gage 1368 sub initialize {
34 :     my ($self) = @_;
35 : gage 1928 my $r = $self->r;
36 :     my $db = $r->db;
37 :     my $ce = $r->ce;
38 :     my $authz = $r->authz;
39 :     my $user = $r->param('user');
40 : gage 1368
41 :     unless ($authz->hasPermissions($user, "send_mail")) {
42 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("You are not authorized to send mail to students.")));
43 : gage 1368 return;
44 :     }
45 : gage 1369 #############################################################################################
46 :     # gather directory data
47 :     #############################################################################################
48 :     my $emailDirectory = $ce->{courseDirs}->{email};
49 :     my $scoringDirectory = $ce->{courseDirs}->{scoring};
50 :     my $templateDirectory = $ce->{courseDirs}->{templates};
51 : gage 1368
52 : gage 1369 my $action = $r->param('action');
53 :     my $openfilename = $r->param('openfilename');
54 :     my $savefilename = $r->param('savefilename');
55 : gage 1370
56 :    
57 :     #FIXME get these values from global course environment (see subroutines as well)
58 :     my $default_msg_file = 'default.msg';
59 :     my $old_default_msg_file = 'old_default.msg';
60 :    
61 : gage 1372
62 : gage 1370 # store data
63 :     $self->{defaultFrom} = 'FIXME from';
64 :     $self->{defaultReply} = 'FIXME reply';
65 :     $self->{rows} = (defined($r->param('rows'))) ? $r->param('rows') : $ce->{mail}->{editor_window_rows};
66 :     $self->{columns} = (defined($r->param('columns'))) ? $r->param('columns') : $ce->{mail}->{editor_window_columns};
67 :     $self->{default_msg_file} = $default_msg_file;
68 :     $self->{old_default_msg_file} = $old_default_msg_file;
69 : gage 1372 $self->{merge_file} = (defined($r->param('merge_file' ))) ? $r->param('merge_file') : 'None';
70 : gage 1376 $self->{preview_user} = (defined($r->param('preview_user'))) ? $r->param('preview_user') : $user;
71 : gage 1372
72 :    
73 :     #############################################################################################
74 :     # gather database data
75 :     #############################################################################################
76 :     # FIXME this might be better done in body? We don't always need all of this data. or do we?
77 : gage 1773 my @users = $db->listUsers;
78 : gage 1372 my @user_records = ();
79 : gage 1667 foreach my $userName (@users) {
80 :     my $userRecord = $db->getUser($userName); # checked
81 :     die "record for user $userName not found" unless $userRecord;
82 :     push(@user_records, $userRecord);
83 :     }
84 : gage 1720 ###########################
85 :     # Sort the users for presentation in the select list
86 :     ###########################
87 :     if (defined $r->param("sort_by") ) {
88 :     my $sort_method = $r->param("sort_by");
89 :     if ($sort_method eq 'section') {
90 :     @user_records = sort { (lc($a->section) cmp lc($b->section)) || (lc($a->last_name) cmp lc($b->last_name)) } @user_records;
91 :     } elsif ($sort_method eq 'recitation') {
92 :     @user_records = sort { (lc($a->recitation) cmp lc($b->recitation)) || (lc($a->last_name) cmp lc($b->last_name)) } @user_records;
93 :     } elsif ($sort_method eq 'alphabetical') {
94 :     @user_records = sort { (lc($a->last_name) cmp lc($b->last_name)) } @user_records;
95 : gage 1773 } elsif ($sort_method eq 'id' ) {
96 :     @user_records = sort { $a->user_id cmp $b->user_id } @user_records;
97 :     }
98 :     } else {
99 :     @user_records = sort { $a->user_id cmp $b->user_id } @user_records;
100 : gage 1720 }
101 : gage 1372
102 : gage 1720
103 :     # replace the user names by a sorted version.
104 :     @users = map {$_->user_id} @user_records;
105 : gage 1372 # store data
106 :     $self->{ra_users} = \@users;
107 :     $self->{ra_user_records} = \@user_records;
108 :    
109 :     #############################################################################################
110 :     # gather list of recipients
111 :     #############################################################################################
112 :     my @send_to = ();
113 :     #FIXME this (radio) is a lousy name
114 :     my $recipients = $r->param('radio');
115 : gage 1375 if (defined($recipients) and $recipients eq 'all_students') { #only active students #FIXME status check??
116 : gage 1372 foreach my $ur (@user_records) {
117 :     push(@send_to,$ur->user_id) if $ur->status eq 'C' and not($ur->user_id =~ /practice/);
118 :     }
119 : gage 1375 } elsif (defined($recipients) and $recipients eq 'studentID' ) {
120 : gage 1372 @send_to = $r->param('classList');
121 :     } else {
122 : gage 1375 # no recipients have been defined -- probably the first time on the page
123 : gage 1372 }
124 :     $self->{ra_send_to} = \@send_to;
125 : gage 1370 #################################################################
126 :     # Check the validity of the input file name
127 :     #################################################################
128 :     my $input_file = '';
129 :     #make sure an input message file was submitted and exists
130 :     #else use the default message
131 :     if ( defined($openfilename) ) {
132 :     if ( -e "${emailDirectory}/$openfilename") {
133 :     if ( -R "${emailDirectory}/$openfilename") {
134 :     $input_file = $openfilename;
135 : gage 1369 } else {
136 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p(join("",
137 : gage 1370 "The file ${emailDirectory}/$openfilename is not readable by the webserver.",CGI::br(),
138 :     "Check that it's permissions are set correctly.",
139 : toenail 2084 ))));
140 : gage 1369 }
141 :     } else {
142 : gage 1370 $input_file = $default_msg_file;
143 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p(join("",
144 : gage 1370 "The file ${emailDirectory}/$openfilename cannot be found.",CGI::br(),
145 :     "Check whether it exists and whether the directory $emailDirectory can be read by the webserver.",CGI::br(),
146 :     "Using contents of the default message $default_msg_file instead.",
147 : toenail 2084 ))));
148 : gage 1369 }
149 : gage 1370 } else {
150 : gage 1372 $input_file = $default_msg_file;
151 : gage 1370 }
152 : gage 1372 $self->{input_file} =$input_file;
153 : gage 1370
154 :     #################################################################
155 :     # Determine the file name to save message into
156 :     #################################################################
157 : gage 1371 my $output_file = 'FIXME no output file specified';
158 : gage 1370 if (defined($action) and $action eq 'Save as Default') {
159 :     $output_file = $default_msg_file;
160 : toenail 2084 } elsif ( defined($action) and ($action =~/save/i)) {
161 :     if (defined($savefilename) and $savefilename ) {
162 :     $output_file = $savefilename;
163 :     } else {
164 :     $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("No filename was specified for saving! The message was not saved.")));
165 :     }
166 : gage 1370 } elsif ( defined($input_file) ) {
167 :     $output_file = $input_file;
168 :     }
169 : gage 1953
170 : gage 1370 #################################################################
171 :     # Sanity check on save file name
172 :     #################################################################
173 :    
174 :     if ($output_file =~ /^[~.]/ || $output_file =~ /\.\./) {
175 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"},
176 :     CGI::p("For security reasons, you cannot specify a message file from a directory",
177 :     "higher than the email directory (you can't use ../blah/blah for example). ",
178 :     "Please specify a different file or move the needed file to the email directory",)));
179 :     }
180 : gage 1371 unless ($output_file =~ m|\.msg$| ) {
181 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"},
182 :     CGI::p("Invalid file name.",
183 : gage 1371 "The file name \"$output_file\" does not have a \".msg\" extension",
184 :     "All email file names must end in the extension \".msg\"",
185 :     "choose a file name with a \".msg\" extension.",
186 : toenail 2084 "The message was not saved.",)));
187 : gage 1371 }
188 : toenail 2084
189 : gage 1371 $self->{output_file} = $output_file; # this is ok. It will be put back in the text input box for re-editing.
190 : gage 1370
191 : toenail 2084
192 : gage 1370 #############################################################################################
193 :     # Determine input source
194 :     #############################################################################################
195 :     my $input_source = ( defined( $r->param('body') ) and $action ne 'Open' ) ? 'form' : 'file';
196 : gage 1953
197 : gage 1370 #############################################################################################
198 :     # Get inputs
199 :     #############################################################################################
200 :     my($from, $replyTo, $r_text, $subject);
201 :     if ($input_source eq 'file') {
202 : gage 1953
203 : gage 1370 ($from, $replyTo,$subject,$r_text) = $self->read_input_file("$emailDirectory/$input_file");
204 :    
205 : gage 1953
206 : gage 1370 } elsif ($input_source eq 'form') {
207 :     # read info from the form
208 :     # bail if there is no message body
209 : gage 1369
210 : gage 1370 $from = $r->param('from');
211 :     $replyTo = $r->param('replyTo');
212 :     $subject = $r->param('subject');
213 :     my $body = $r->param('body');
214 :     # Sanity check: body must contain non-white space
215 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p('You didn\'t enter any message.'))) unless ($r->param('body') =~ /\S/);
216 : gage 1370 $r_text = \$body;
217 : gage 1369
218 : gage 1370 }
219 :     # store data
220 :     $self->{from} = $from;
221 :     $self->{replyTo} = $replyTo;
222 :     $self->{subject} = $subject;
223 :     $self->{r_text} = $r_text;
224 :    
225 :    
226 : gage 1372
227 :     ###################################################################################
228 :     #Determine the appropriate script action from the buttons
229 :     ###################################################################################
230 :     # first time actions
231 :     # open new file
232 :     # open default file
233 :     # choose merge file actions
234 :     # chose merge button
235 :     # option actions
236 :     # 'reset rows'
237 :    
238 :     # save actions
239 :     # "save" button
240 :     # "save as" button
241 :     # "save as default" button
242 :     # preview actions
243 :     # 'preview' button
244 :     # email actions
245 :     # 'entire class'
246 :     # 'selected studentIDs'
247 :     # error actions (various)
248 :    
249 :    
250 : gage 1369 #############################################################################################
251 : gage 1370 # if no form is submitted, gather data needed to produce the mail form and return
252 : gage 1369 #############################################################################################
253 : gage 1372 my $to = $r->param('To');
254 :     my $script_action = '';
255 :    
256 :    
257 : gage 1773 if(not defined($action) or $action eq 'Open' or $action eq $REFRESH_RESIZE_BUTTON or $action eq 'Sort by'
258 : gage 1375 or $action eq 'Set merge file to:' ){
259 : gage 1953
260 : gage 1369 return '';
261 :     }
262 :    
263 :    
264 :    
265 :    
266 :    
267 :     #############################################################################################
268 : gage 1370 # If form is submitted deal with filled out forms
269 : gage 1369 # and various actions resulting from different buttons
270 :     #############################################################################################
271 :    
272 : gage 1372
273 : gage 1370 if ($action eq 'Save' or $action eq 'Save as:' or $action eq 'Save as Default') {
274 :    
275 :     # warn "FIXME Saving files action = $action outputFileName=$output_file";
276 : gage 1369
277 : gage 1370 #################################################################
278 :     # construct message body
279 :     #################################################################
280 :     my $temp_body = ${ $r_text };
281 :     $temp_body =~ s/\r\n/\n/g;
282 :     $temp_body = join("",
283 :     "From: $from \nReply-To: $replyTo\n" ,
284 :     "Subject: $subject\n" ,
285 :     "Message: \n $temp_body");
286 :     # warn "FIXME from $from | subject $subject |reply $replyTo|msg $temp_body";
287 :     #################################################################
288 :     # overwrite protection
289 :     #################################################################
290 :     if ($action eq 'Save as:' and -e "$emailDirectory/$output_file") {
291 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"},
292 :     CGI::p("The file $emailDirectory/$output_file already exists and cannot be overwritten",
293 :     "The message was not saved")));
294 :     return;
295 : gage 1370 }
296 :    
297 :     #################################################################
298 :     # Back up existing file?
299 :     #################################################################
300 : gage 1371 if ($action eq 'Save as Default' and -e "$emailDirectory/$default_msg_file") {
301 :     rename("$emailDirectory/$default_msg_file","$emailDirectory/$old_default_msg_file") or
302 :     die "Can't rename $emailDirectory/$default_msg_file to $emailDirectory/$old_default_msg_file ",
303 :     "Check permissions for webserver on directory $emailDirectory. $!";
304 : toenail 2095 $self->addmessage(CGI::div({class=>"ResultsWithoutError"}, CGI::p("Backup file <code>$emailDirectory/$old_default_msg_file</code> created.".CGI::br())));
305 : gage 1370 }
306 :     #################################################################
307 :     # Save the message
308 :     #################################################################
309 : toenail 2084 $self->saveProblem($temp_body, "${emailDirectory}/$output_file" ) unless ($output_file =~ /^[~.]/ || $output_file =~ /\.\./ || not $output_file =~ m|\.msg$|);
310 :     unless ( $self->{submit_message} or not -w "${emailDirectory}/$output_file" ) { # if there are no errors report success
311 : toenail 2095 $self->addmessage(CGI::div({class=>"ResultsWithoutError"}, CGI::p("Message saved to file <code>${emailDirectory}/$output_file</code>.")));
312 : gage 1953 }
313 :    
314 : gage 2050 } elsif ($action eq 'Preview message') {
315 : gage 1372 $self->{response} = 'preview';
316 : gage 1370
317 :     } elsif ($action eq 'Send Email') {
318 : gage 1373 $self->{response} = 'send_email';
319 :    
320 :     my @recipients = @{$self->{ra_send_to}};
321 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"},
322 :     CGI::p("No recipients selected "))) unless @recipients;
323 : gage 1373 # get merge file
324 :     my $merge_file = ( defined($self->{merge_file}) ) ? $self->{merge_file} : 'None';
325 :     my $delimiter = ',';
326 : gage 1397 my $rh_merge_data = $self->read_scoring_file("$merge_file", "$delimiter");
327 : gage 1376 unless (ref($rh_merge_data) ) {
328 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("No merge data file")));
329 :     $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("Can't read merge file $merge_file. No message sent")));
330 : gage 1376 return;
331 :     } ;
332 : gage 1373
333 : gage 1376
334 : gage 1373 foreach my $recipient (@recipients) {
335 :     #warn "FIXME sending email to $recipient";
336 : gage 1667 my $ur = $self->{db}->getUser($recipient); #checked
337 :     die "record for user $recipient not found" unless $ur;
338 : sh002i 1677 unless ($ur->email_address) {
339 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"},
340 :     CGI::p("user $recipient does not have an email address -- skipping")));
341 : sh002i 1677 next;
342 :     }
343 : gage 1373 my ($msg, $preview_header);
344 :     eval{ ($msg,$preview_header) = $self->process_message($ur,$rh_merge_data); };
345 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("There were errors in processing user $ur, merge file $merge_file. $@"))) if $@;
346 : gage 1373 my $mailer = Mail::Sender->new({
347 :     from => $from,
348 :     to => $ur->email_address,
349 :     smtp => $ce->{mail}->{smtpServer},
350 :     subject => $subject,
351 :     headers => "X-Remote-Host: ".$r->get_remote_host(),
352 :     });
353 :     unless (ref $mailer) {
354 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("Failed to create a mailer for user $recipient: $Mail::Sender::Error")));
355 : gage 1373 next;
356 :     }
357 :     unless (ref $mailer->Open()) {
358 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("Failed to open the mailer for user $recipient: $Mail::Sender::Error")));
359 : gage 1373 next;
360 :     }
361 : toenail 2084 my $MAIL = $mailer->GetHandle() or $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("Couldn't get handle")));
362 :     print $MAIL $msg || $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("Couldn't print to $MAIL")));
363 :     close $MAIL || $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("Couldn't close $MAIL")));
364 : gage 1373 #warn "FIXME mailed to ", $ur->email_address, "from $from subject $subject";
365 :    
366 :     }
367 :    
368 : gage 1370 } else {
369 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("Didn't recognize button $action")));
370 : gage 1370 }
371 : gage 1369
372 :    
373 : toenail 2084
374 : gage 1369 } #end initialize
375 :    
376 : gage 1368
377 :    
378 :    
379 : gage 1928
380 : gage 1368 sub body {
381 : gage 1928 my ($self) = @_;
382 :     my $r = $self->r;
383 :     my $urlpath = $r->urlpath;
384 :     my $setID = $urlpath->arg("setID");
385 : gage 1372 my $response = (defined($self->{response}))? $self->{response} : '';
386 :     if ($response eq 'preview') {
387 :     $self->print_preview($setID);
388 : gage 1373 } elsif (($response eq 'send_email')){
389 : toenail 2095 $self->addmessage(CGI::div({class=>"ResultsWithoutError"}, CGI::p("Email sent to ". scalar(@{$self->{ra_send_to}})." students.")));
390 : gage 2051 $self->{message} .= CGI::i("Email sent to ". scalar(@{$self->{ra_send_to}})." students.");
391 : gage 1372 $self->print_form($setID);
392 : gage 1375 } else {
393 :     $self->print_form($setID);
394 : gage 1372 }
395 :    
396 :     }
397 :     sub print_preview {
398 : gage 1928 my ($self) = @_;
399 :     my $r = $self->r;
400 :     my $urlpath = $r->urlpath;
401 :     my $setID = $urlpath->arg("setID");
402 :    
403 : gage 1372 # get preview user
404 : gage 1928 my $ur = $r->db->getUser($self->{preview_user}); #checked
405 : gage 1667 die "record for preview user ".$self->{preview_user}. " not found." unless $ur;
406 : gage 1372
407 :     # get merge file
408 :     my $merge_file = ( defined($self->{merge_file}) ) ? $self->{merge_file} : 'None';
409 :     my $delimiter = ',';
410 : gage 1397 my $rh_merge_data = $self->read_scoring_file("$merge_file", "$delimiter");
411 : gage 1372
412 :     my ($msg, $preview_header) = $self->process_message($ur,$rh_merge_data);
413 :    
414 :     my $recipients = join(" ",@{$self->{ra_send_to} });
415 : toenail 2084 my $errorMessage = defined($self->{submit_message}) ? CGI::i($self->{submit_message} ) : '' ;
416 : gage 1373 $msg = join("",
417 :     $errorMessage,
418 :     $preview_header,
419 :     "To: " , $ur->email_address,"\n",
420 :     "From: " , $self->{from} , "\n" ,
421 :     "Reply-To: " , $self->{replyTo} , "\n" ,
422 :     "Subject: " , $self->{subject} , "\n" ,"\n" ,
423 :     $msg , "\n"
424 :     );
425 : gage 1372
426 : gage 1373 return join("", '<pre>',$msg,"\n","\n",
427 : gage 1372 '</pre>',
428 :     CGI::p('Use browser back button to return from preview mode'),
429 :     CGI::h3('Emails to be sent to the following:'),
430 :     $recipients, "\n",
431 :    
432 :     );
433 :    
434 :     }
435 :     sub print_form {
436 : gage 1928 my ($self) = @_;
437 :     my $r = $self->r;
438 :     my $urlpath = $r->urlpath;
439 :     my $authz = $r->authz;
440 :     my $db = $r->db;
441 :     my $ce = $r->ce;
442 :     my $courseName = $urlpath->arg("courseID");
443 :     my $setID = $urlpath->arg("setID");
444 :     my $user = $r->param('user');
445 :    
446 : gage 1938 my $root = $ce->{webworkURLs}->{root};
447 :     my $sendMailPage = $urlpath->newFromModule($urlpath->module,courseID=>$courseName);
448 :     my $sendMailURL = $self->systemLink($sendMailPage, authen => 0);
449 : gage 1368
450 : toenail 2084 return CGI::em("You are not authorized to access the Instructor tools.") unless $authz->hasPermissions($user, "access_instructor_tools");
451 : gage 1368
452 :     my $userTemplate = $db->newUser;
453 :     my $permissionLevelTemplate = $db->newPermissionLevel;
454 :    
455 :     # This code will require changing if the permission and user tables ever have different keys.
456 : gage 1372 my @users = @{ $self->{ra_users} };
457 :     my $ra_user_records = $self->{ra_user_records};
458 :     my %classlistLabels = ();# %$hr_classlistLabels;
459 :     foreach my $ur (@{ $ra_user_records }) {
460 : gage 1720 $classlistLabels{$ur->user_id} = $ur->user_id.': '.$ur->last_name. ', '. $ur->first_name.' -- '.$ur->section." / ".$ur->recitation;
461 : gage 1372 }
462 : gage 1368
463 :    
464 :     ##############################################################################################################
465 :    
466 : gage 1372
467 : gage 1369 my $from = $self->{from};
468 :     my $subject = $self->{subject};
469 :     my $replyTo = $self->{replyTo};
470 :     my $columns = $self->{columns};
471 :     my $rows = $self->{rows};
472 : gage 1370 my $text = defined($self->{r_text}) ? ${ $self->{r_text} }: 'FIXME no text was produced by initialization!!';
473 :     my $input_file = $self->{input_file};
474 :     my $output_file = $self->{output_file};
475 : gage 1371 my @sorted_messages = $self->get_message_file_names;
476 :     my @sorted_merge_files = $self->get_merge_file_names;
477 :     my $merge_file = ( defined($self->{merge_file}) ) ? $self->{merge_file} : 'None';
478 : gage 1372 my $delimiter = ',';
479 : gage 1397 my $rh_merge_data = $self->read_scoring_file("$merge_file", "$delimiter");
480 : gage 1372 my @merge_keys = keys %$rh_merge_data;
481 :     my $preview_user = $self->{preview_user};
482 : gage 1667 my $preview_record = $db->getUser($preview_user); # checked
483 :     die "record for preview user ".$self->{preview_user}. " not found." unless $preview_record;
484 : gage 1372
485 : gage 1667
486 : gage 1372 #############################################################################################
487 :    
488 : gage 1938 print CGI::start_form({method=>"post", action=>$sendMailURL});
489 : gage 1372 print $self->hidden_authen_fields();
490 :     #############################################################################################
491 :     # begin upper table
492 :     #############################################################################################
493 :    
494 : gage 1368 print CGI::start_table({-border=>'2', -cellpadding=>'4'});
495 : gage 1720 print CGI::Tr({-align=>'left',-valign=>'top'},
496 : gage 1372 #############################################################################################
497 :     # first column
498 :     #############################################################################################
499 :    
500 : gage 1720 CGI::td(CGI::strong("Message file: $input_file"),"\n",CGI::br(),
501 : gage 1371 CGI::submit(-name=>'action', -value=>'Open'), '&nbsp;&nbsp;&nbsp;&nbsp;',"\n",
502 :     CGI::popup_menu(-name=>'openfilename',
503 :     -values=>\@sorted_messages,
504 :     -default=>$input_file
505 :     ), "\n",CGI::br(),
506 :    
507 :     "Save file to: $output_file","\n",CGI::br(),
508 : gage 1370 "\n", 'From:','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', CGI::textfield(-name=>"from", -size=>30, -value=>$from, -override=>1),
509 :     "\n", CGI::br(),'Reply-To: ', CGI::textfield(-name=>"replyTo", -size=>30, -value=>$replyTo, -override=>1),
510 : gage 1376 "\n", CGI::br(),'Subject: ', CGI::br(), CGI::textarea(-name=>'subject', -default=>$subject, -rows=>3,-columns=>30, -override=>1),
511 : gage 1370 ),
512 : gage 1372 #############################################################################################
513 :     # second column
514 :     #############################################################################################
515 : gage 1773 CGI::td({-align=>'left',style=>'font-size:smaller'},
516 :    
517 :     CGI::strong("Send to:"),
518 : gage 1720 CGI::radio_group(-name=>'radio', -values=>['all_students','studentID'],
519 :     -labels=>{all_students=>'All',studentID => 'Selected'},
520 :     -default=>'studentID',
521 : gage 1773 -linebreak=>0
522 :     ), CGI::br(),CGI::br(),
523 :    
524 :     CGI::input({type=>'submit',value=>'Sort by',name=>'action'}),,
525 : gage 1720 CGI::radio_group(-name=>'sort_by', -values=>['id','alphabetical','section','recitation'],
526 : gage 1773 -labels=>{id=>'Login',alphabetical=>'Alph.',section => 'Sec.',recitation=>'Rec.'},
527 : gage 1720 -default=>defined($r->param("sort_by")) ? $r->param("sort_by") : 'id',
528 : gage 1773 -linebreak=>0
529 : gage 1720 ),
530 :    
531 : gage 1773 CGI::br(),CGI::br(),
532 : gage 1720 CGI::popup_menu(-name=>'classList',
533 :     -values=>\@users,
534 :     -labels=>\%classlistLabels,
535 :     -size => 10,
536 :     -multiple => 1,
537 :     -default=>$user
538 :     ),
539 :     ),
540 : gage 1370
541 : gage 1720
542 : gage 1372 #############################################################################################
543 :     # third column
544 :     #############################################################################################
545 : gage 1370 CGI::td({align=>'left'},
546 : gage 1720 "<b>Merge file:</b> $merge_file", CGI::br(),
547 : gage 1375 CGI::submit(-name=>'action', -value=>'Set merge file to:'),CGI::br(),
548 : gage 1371 CGI::popup_menu(-name=>'merge_file',
549 :     -values=>\@sorted_merge_files,
550 :     -default=>$merge_file,
551 : gage 2050 ), "\n",CGI::hr(),
552 :     CGI::b("Viewing email for: "), "$preview_user",CGI::br(),
553 :     CGI::submit(-name=>'action', -value=>'resize', -label=>$REFRESH_RESIZE_BUTTON),'&nbsp;',
554 : gage 1372 CGI::popup_menu(-name=>'preview_user',
555 : gage 1370 -values=>\@users,
556 : gage 1372 #-labels=>\%classlistLabels,
557 :     -default=>$preview_user,
558 : gage 1369 ),
559 : gage 2050 CGI::br(),
560 :     CGI::submit(-name=>'action', -value=>'preview',-label=>'Preview message'),'&nbsp;&nbsp;',
561 :    
562 :     CGI::br(),
563 :    
564 : gage 1372 CGI::hr(),
565 : gage 1370 " Rows: ", CGI::textfield(-name=>'rows', -size=>3, -value=>$rows),
566 :     " Columns: ", CGI::textfield(-name=>'columns', -size=>3, -value=>$columns),
567 : gage 2050 CGI::br(),CGI::i('Press any action button to update display'),CGI::br(),
568 : gage 1370 #show available macros
569 :     CGI::popup_menu(
570 :     -name=>'dummyName',
571 :     -values=>['', '$SID', '$FN', '$LN', '$SECTION', '$RECITATION','$STATUS', '$EMAIL', '$LOGIN', '$COL[3]', '$COL[-1]'],
572 :     -labels=>{''=>'list of insertable macros',
573 :     '$SID'=>'$SID - Student ID',
574 :     '$FN'=>'$FN - First name',
575 :     '$LN'=>'$LN - Last name',
576 : gage 1372 '$SECTION'=>'$SECTION',
577 : gage 1370 '$RECITATION'=>'$RECITATION',
578 :     '$STATUS'=>'$STATUS - C, Audit, Drop, etc.',
579 :     '$EMAIL'=>'$EMAIL - Email address',
580 :     '$LOGIN'=>'$LOGIN - Login',
581 : gage 1372 '$COL[3]'=>'$COL[3] - 3rd col',
582 : gage 1370 '$COL[-1]'=>'$COL[-1] - Last column'
583 :     }
584 :     ), "\n",
585 :     ),
586 : gage 1368
587 : gage 1370 ); # end Tr
588 : gage 1372 print CGI::end_table();
589 :     #############################################################################################
590 :     # end upper table
591 :     #############################################################################################
592 :    
593 :     # show merge file
594 :     # print "<pre>",(map {$_ =~s/\s/\./g;$_} map {sprintf('%-8.8s',$_);} 0..8),"</pre>";
595 :     # print CGI::popup_menu(
596 :     # -name=>'dummyName2',
597 :     # -values=>\@merge_keys,
598 :     # -labels=>$rh_merge_data,
599 :     # -multiple=>1,
600 :     # -size =>2,
601 :     #
602 :     # ), "\n",CGI::br();
603 :     # warn "merge keys ", join( " ",@merge_keys);
604 :     #############################################################################################
605 :     # merge file fragment and message text area field
606 :     #############################################################################################
607 : gage 1373 my @tmp2;
608 : gage 1667 eval{ @tmp2= @{$rh_merge_data->{ $db->getUser($preview_user)->student_id } };}; # checked
609 : gage 1730 if ($@ and $merge_file ne 'None') {
610 : gage 1381 print "No merge data for $preview_user in merge file: &lt;$merge_file&gt;",CGI::br();
611 : gage 1373 } else {
612 : gage 1950 print CGI::pre("",data_format(0..($#tmp2)),"<br>", data_format2(@tmp2));
613 : gage 1373 }
614 : gage 1368 #create a textbox with the subject and a textarea with the message
615 :     #print actual body of message
616 : gage 1369
617 : gage 1370 print "\n", CGI::p( $self->{message}) if defined($self->{message});
618 : gage 1369 print "\n", CGI::p( CGI::textarea(-name=>'body', -default=>$text, -rows=>$rows, -columns=>$columns, -override=>1));
619 : gage 1372
620 :     #############################################################################################
621 :     # action button table
622 :     #############################################################################################
623 : gage 1370 print CGI::table( { -border=>2,-cellpadding=>4},
624 :     CGI::Tr(
625 :     CGI::td( CGI::submit(-name=>'action', -value=>'Send Email') ), "\n",
626 :     CGI::td(CGI::submit(-name=>'action', -value=>'Save')," to $output_file"), " \n",
627 :     CGI::td(CGI::submit(-name=>'action', -value=>'Save as:'),
628 :     CGI::textfield(-name=>'savefilename', -size => 20, -value=> "$output_file", -override=>1)
629 :     ), "\n",
630 :     CGI::td(CGI::submit(-name=>'action', -value=>'Save as Default')),
631 :     )
632 :     );
633 : gage 1368
634 :     ##############################################################################################################
635 : gage 1369
636 :     print CGI::end_form();
637 : gage 1368 return "";
638 :     }
639 :    
640 : gage 1369 ##############################################################################
641 :     # Utility methods
642 :     ##############################################################################
643 : gage 1370 sub submission_error {
644 : gage 1369 my $self = shift;
645 : toenail 2084 my $msg = join( " ", @_);
646 : gage 1730 $self->{submitError} .= CGI::br().$msg;
647 : toenail 2084 return;
648 : gage 1369 }
649 :    
650 : gage 1370 sub saveProblem {
651 :     my $self = shift;
652 :     my ($body, $probFileName)= @_;
653 :     local(*PROBLEM);
654 :     open (PROBLEM, ">$probFileName") ||
655 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"},
656 :     CGI::p("Could not open $probFileName for writing.
657 :     Check that the permissions for this problem are 660 (-rw-rw----)")));
658 :     print PROBLEM $body if -w $probFileName;
659 : gage 1370 close PROBLEM;
660 :     chmod 0660, "$probFileName" ||
661 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"},
662 :     CGI::p("
663 :     CAN'T CHANGE PERMISSIONS ON FILE $probFileName")));
664 : gage 1370 }
665 :    
666 :     sub read_input_file {
667 :     my $self = shift;
668 :     my $filePath = shift;
669 :     my ($text, @text);
670 :     my $header = '';
671 :     my ($subject, $from, $replyTo);
672 :     local(*FILE);
673 : gage 1371 if (-e "$filePath" and -r "$filePath") {
674 : toenail 2084 open FILE, "$filePath" || do { $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("Can't open $filePath"))); return};
675 : gage 1371 while ($header !~ s/Message:\s*$//m and not eof(FILE)) {
676 : gage 1370 $header .= <FILE>;
677 :     }
678 :     $text = join( '', <FILE>);
679 :     $text =~ s/^\s*//; # remove initial white space if any.
680 :     $header =~ /^From:\s(.*)$/m;
681 :     $from = $1 or $from = $self->{defaultFrom};
682 :    
683 :     $header =~ /^Reply-To:\s(.*)$/m;
684 :     $replyTo = $1 or $replyTo = $self->{defaultReply};
685 :    
686 :     $header =~ /^Subject:\s(.*)$/m;
687 :     $subject = $1;
688 :    
689 :     } else {
690 :     $from = $self->{defaultFrom};
691 :     $replyTo = $self->{defaultReply};
692 : gage 1371 $text = (-e "$filePath") ? "FIXME file $filePath can't be read" :"FIXME file $filePath doesn't exist";
693 : gage 1370 $subject = "FIXME default subject";
694 :     }
695 :     return ($from, $replyTo, $subject, \$text);
696 :     }
697 : gage 1371
698 :    
699 : gage 1397 sub get_message_file_names {
700 :     my $self = shift;
701 :     return $self->read_dir($self->{ce}->{courseDirs}->{email}, '\\.msg$');
702 : gage 1371 }
703 : gage 1397 sub get_merge_file_names {
704 :     my $self = shift;
705 : gage 1730 return 'None', $self->read_dir($self->{ce}->{courseDirs}->{scoring}, '\\.csv$'); #FIXME ? check that only readable files are listed.
706 : gage 1371 }
707 : gage 1372
708 : gage 1397
709 : gage 1372 sub getRecord {
710 :     my $self = shift;
711 :     my $line = shift;
712 :     my $delimiter = shift;
713 :     $delimiter = ',' unless defined($delimiter);
714 :    
715 :     # Takes a delimited line as a parameter and returns an
716 :     # array. Note that all white space is removed. If the
717 :     # last field is empty, the last element of the returned
718 :     # array is also empty (unlike what the perl split command
719 :     # would return). E.G. @lineArray=&getRecord(\$delimitedLine).
720 :    
721 :     my(@lineArray);
722 : gage 2001 $line.="${delimiter}___"; # add final field which must be non-empty
723 :     @lineArray = split(/\s*${delimiter}\s*/,$line); # split line into fields
724 : gage 1372 $lineArray[0] =~s/^\s*//; # remove white space from first element
725 : gage 2001 pop @lineArray; # remove the last artificial field
726 : gage 1372 @lineArray;
727 :     }
728 :    
729 :     sub process_message {
730 :     my $self = shift;
731 :     my $ur = shift;
732 :     my $rh_merge_data = shift;
733 :     my $text = defined($self->{r_text}) ? ${ $self->{r_text} }:
734 : gage 1730 'FIXME no text was produced by initialization!!';
735 :     my $merge_file = ( defined($self->{merge_file}) ) ? $self->{merge_file} : 'None';
736 : gage 1372 #user macros that can be used in the email message
737 :     my $SID = $ur->student_id;
738 :     my $FN = $ur->first_name;
739 :     my $LN = $ur->last_name;
740 :     my $SECTION = $ur->section;
741 :     my $RECITATION = $ur->recitation;
742 :     my $STATUS = $ur->status;
743 :     my $EMAIL = $ur->email_address;
744 :     my $LOGIN = $ur->user_id;
745 : gage 1730
746 : gage 1372 # get record from merge file
747 :     # FIXME this is inefficient. The info should be cached
748 : gage 1373 my @COL = defined($rh_merge_data->{$SID}) ? @{$rh_merge_data->{$SID} } : ();
749 : gage 1730 if ($merge_file ne 'None' && not defined($rh_merge_data->{$SID}) ) {
750 : toenail 2084 $self->addmessage(CGI::div({class=>"ResultsWithError"}, CGI::p("No merge data for student id:$SID; name:$FN $LN; login:$LOGIN")));
751 : gage 1730 }
752 : gage 1372
753 :     my $endCol = @COL;
754 :     # for safety, only evaluate special variables
755 : gage 1373 my $msg = $text;
756 :     $msg =~ s/(\$SID)/eval($1)/ge;
757 :     $msg =~ s/(\$LN)/eval($1)/ge;
758 :     $msg =~ s/(\$FN)/eval($1)/ge;
759 :     $msg =~ s/(\$STATUS)/eval($1)/ge;
760 :     $msg =~ s/(\$SECTION)/eval($1)/ge;
761 :     $msg =~ s/(\$RECITATION)/eval($1)/ge;
762 :     $msg =~ s/(\$EMAIL)/eval($1)/ge;
763 :     $msg =~ s/(\$LOGIN)/eval($1)/ge;
764 :     $msg =~ s/\$COL\[ *-/\$COL\[$endCol-/g;
765 : gage 2049 $msg =~ s/(\$COL\[.*?\])/eval($1)/ge if defined($COL[0]); # prevents extraneous error messages.
766 : gage 1373
767 :     $msg =~ s/\r//g;
768 : gage 1372
769 : gage 1950 my $preview_header = CGI::pre("",data_format(0..($#COL)),"<br>", data_format2(@COL)).
770 : gage 1372 CGI::h3( "This sample mail would be sent to $EMAIL");
771 :    
772 :    
773 :     return $msg, $preview_header;
774 :     }
775 : gage 1948
776 :    
777 :     # Ê sub data_format {
778 :     #
779 :     # Ê Ê Ê Ê Êmap {$_ =~s/\s/\./g;$_} Ê Ê map {sprintf('%-8.8s',$_);} Ê@_;
780 : gage 1372 sub data_format {
781 : gage 1948 map {"COL[$_]".'&nbsp;'x(3-length($_));} @_; # problems if $_ has length bigger than 4
782 : gage 1372 }
783 : gage 1947 sub data_format2 {
784 : gage 1948 map {$_ =~s/\s/&nbsp;/g;$_} map {sprintf('%-8.8s',$_);} @_;
785 : gage 1947 }
786 : gage 1368 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9