[system] / branches / rel-2-1-a1 / webwork2 / lib / WeBWorK / ContentGenerator.pm Repository:
ViewVC logotype

Annotation of /branches/rel-2-1-a1/webwork2/lib/WeBWorK/ContentGenerator.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1169 - (view) (download) (as text)
Original Path: trunk/webwork2/lib/WeBWorK/ContentGenerator.pm

1 : sh002i 455 ################################################################################
2 : sh002i 494 # WeBWorK mod_perl (c) 2000-2002 WeBWorK Project
3 : sh002i 455 # $Id$
4 :     ################################################################################
5 :    
6 : malsyned 313 package WeBWorK::ContentGenerator;
7 : malsyned 305
8 : sh002i 455 =head1 NAME
9 :    
10 :     WeBWorK::ContentGenerator - base class for modules that generate page content.
11 :    
12 :     =cut
13 :    
14 : malsyned 441 use strict;
15 :     use warnings;
16 : malsyned 323 use Apache::Constants qw(:common);
17 : sh002i 455 use CGI qw();
18 : sh002i 469 use URI::Escape;
19 : sh002i 817 use WeBWorK::DB;
20 : sh002i 476 use WeBWorK::Utils qw(readFile);
21 : malsyned 1017 use WeBWorK::Authz;
22 : malsyned 390
23 : sh002i 469 ################################################################################
24 :     # This is a very unruly file, so I'm going to use very large comments to divide
25 :     # it into logical sections.
26 :     ################################################################################
27 : malsyned 390
28 : sh002i 817 # new(Apache::Request, WeBWorK::CourseEnvironment) - create a new instance of a
29 : sh002i 469 # content generator. Usually only called by the dispatcher, although one might
30 :     # be able to use it for things like "sub-requests". Uh... uh... I have to think
31 :     # about that one. The dispatcher uses this idiom:
32 :     #
33 :     # WeBWorK::ContentGenerator::WHATEVER->new($r, $ce)->go(@whatever);
34 :     #
35 :     # and throws away the result ;)
36 :     #
37 : sh002i 819 sub new($$$$) {
38 :     my ($invocant, $r, $ce, $db) = @_;
39 : malsyned 323 my $class = ref($invocant) || $invocant;
40 : sh002i 809 my $self = {
41 :     r => $r,
42 :     ce => $ce,
43 : sh002i 819 db => $db,
44 : malsyned 1017 authz => WeBWorK::Authz->new($r, $ce, $db)
45 : sh002i 809 };
46 : malsyned 305 bless $self, $class;
47 :     return $self;
48 :     }
49 :    
50 : sh002i 469 ################################################################################
51 :     # Invocation and template processing
52 :     ################################################################################
53 : malsyned 323
54 : sh002i 469 # go(@otherArguments) - render a page, using methods from the particular
55 :     # subclass of ContentGenerator. @otherArguments is passed to each method, so
56 :     # that the dispatcher can pass CG-specific data. The order of calls looks like
57 :     # this:
58 :     #
59 :     # * &pre_header_initialize - give subclasses a chance to do initialization
60 :     # necessary for generating the HTTP header.
61 :     # * &header - this class provides a standard HTTP header with Content-Type
62 :     # text/html. Subclasses are welcome to overload this for things like
63 :     # an image-creation content generator or a PDF generator.
64 :     # * &initialize - let subclasses do post-header initialization.
65 :     # * any "template escapes" defined in the system template and supported by
66 :     # the subclass. Generic implementations of &title and &body are provided.
67 :     #
68 :     sub go {
69 :     my $self = shift;
70 :     my $r = $self->{r};
71 : sh002i 809 my $courseEnvironment = $self->{ce};
72 : sh002i 1131
73 : sh002i 469 $self->pre_header_initialize(@_) if $self->can("pre_header_initialize");
74 :     $self->header(@_);
75 :     return OK if $r->header_only;
76 : malsyned 313
77 : sh002i 469 $self->initialize(@_) if $self->can("initialize");
78 :     $self->template($courseEnvironment->{templates}->{system}, @_);
79 : malsyned 441
80 : sh002i 469 return OK;
81 :     }
82 :    
83 :     # template(STRING, @otherArguments) - parse a template, looking for escapes of
84 :     # the form <!--#NAME ARG1="FOO" ARG2="BAR"--> and calling a member function NAME
85 :     # (if available) for each NAME. The escapes are called like:
86 :     #
87 :     # $self->NAME(@otherArguments, \%escapeArguments)
88 :     #
89 :     # where @otherArguments originates in the dispatcher and %escapeArguments is
90 :     # parsed out of the escape itself (i.e. ARG1 => FOO, ARG2 => BAR)
91 :     #
92 :     sub template {
93 :     my ($self, $templateFile) = (shift, shift);
94 :     my $r = $self->{r};
95 : sh002i 809 my $courseEnvironment = $self->{ce};
96 : malsyned 512 my @ifstack = (1); # Start off in printing mode
97 :     # say $ifstack[-1] to get the result of the last <#!--if-->
98 : sh002i 469
99 : sh002i 476 # so even though the variable $/ APPEARS to contain a newline,
100 :     # <TEMPLATE> is slurping the whole file into the first element of
101 :     # @template ONLY AFTER THE TRANSLATOR RUNS. WTF!!!
102 :     #
103 :     #open(TEMPLATE, $templateFile) or die "Couldn't open template $templateFile";
104 :     #my @template = <TEMPLATE>;
105 :     #close TEMPLATE;
106 :     #
107 :     # Let's try something else instead:
108 :     my @template = split /\n/, readFile($templateFile);
109 :    
110 : sh002i 469 foreach my $line (@template) {
111 :     # This is incremental regex processing.
112 :     # the /c is so that pos($line) doesn't die when the regex fails.
113 :     while ($line =~ m/\G(.*?)<!--#(\w*)((?:\s+.*?)?)-->/gc) {
114 :     my ($before, $function, $raw_args) = ($1, $2, $3);
115 : sh002i 555 my @args = ($raw_args =~ /\S/) ? cook_args($raw_args) : ();
116 :    
117 : malsyned 512 if ($ifstack[-1]) {
118 :     print $before;
119 :     }
120 : sh002i 555
121 : sh002i 558 if ($function eq "if") {
122 : malsyned 748 # a predicate can only be true if everything else on the ifstack is already true, for ANDing
123 :     push @ifstack, ($self->$function(@_, [@args]) && $ifstack[-1]);
124 : sh002i 558 } elsif ($function eq "else" and @ifstack > 1) {
125 :     $ifstack[-1] = not $ifstack[-1];
126 :     } elsif ($function eq "endif" and @ifstack > 1) {
127 :     pop @ifstack;
128 :     } elsif ($ifstack[-1]) {
129 : sh002i 562 if ($self->can($function)) {
130 : malsyned 1042 my @result = $self->$function(@_, {@args});
131 :     if (@result) {
132 :     print @result;
133 :     } else {
134 :     warn "Template escape $function returned an empty list.";
135 : malsyned 1017 }
136 : sh002i 562 }
137 : sh002i 476 }
138 : malsyned 313 }
139 : sh002i 469
140 : malsyned 512 if ($ifstack[-1]) {
141 : sh002i 562 print substr($line, (defined pos $line) ? pos $line : 0), "\n";
142 : malsyned 512 }
143 : malsyned 313 }
144 : sh002i 469 }
145 :    
146 :     # cook_args(STRING) - parses a string of the form ARG1="FOO" ARG2="BAR". Returns
147 : malsyned 512 # a list which pairs into key/values and fits nicely in {}s.
148 : sh002i 469 #
149 : sh002i 798 sub cook_args($) { # ... also used by bin/wwdb, so watch out
150 : sh002i 469 my ($raw_args) = @_;
151 : malsyned 512 my @args = ();
152 : malsyned 353
153 : malsyned 508 # Boy I love m//g in scalar context! Go read the camel book, heathen.
154 :     # First, get the whole token with the quotes on both ends...
155 :     while ($raw_args =~ m/\G\s*(\w*)="((?:[^"\\]|\\.)*)"/g) {
156 :     my ($key, $value) = ($1, $2);
157 :     # ... then, rip out all the protecty backspaces
158 : malsyned 522 $value =~ s/\\(.)/$1/g;
159 : malsyned 512 push @args, $key => $value;
160 : sh002i 469 }
161 :    
162 : malsyned 512 return @args;
163 : malsyned 313 }
164 :    
165 : sh002i 558 # This is different. It probably shouldn't print anything (except in debugging cases)
166 :     # and it should return a boolean, not a string. &if is called in a nonstandard way
167 :     # by &template, with $args as an arrayref instead of a hashref. this is a hack! yay!
168 :    
169 :     # OK, this is a pluggin architecture. it iterates through attributes of the "if" tag,
170 :     # and for each predicate $p, it calls &if_$p in an object-oriented way, continuing the
171 :     # grand templating theme of an object-oriented pluggable architecture using ->can($).
172 :     sub if {
173 :     my ($self, $args) = @_[0,-1];
174 :     # A single if "or"s it's components. Nesting produces "and".
175 :    
176 :     my @args = @$args; # Hahahahaha, get it?!
177 :    
178 :     if (@args % 2 != 0) {
179 :     # flip out and kill people, but do not commit seppuku
180 :     print '<!--&if recieved an uneven number of arguments. This shouldn\'t happen, but I\'ll let it slide.-->\n';
181 :     }
182 :    
183 :     while (@args > 1) {
184 :     my ($key, $value) = (shift @args, shift @args);
185 :    
186 :     # a non-existent &if_$key is the same as a false result, but we're ORing, so it's OK
187 :     my $sub = "if_$key"; # perl doesn't like it when you try to construct a string right in a method invocation
188 :     if ($self->can("if_$key") and $self->$sub("$value")) {
189 :     return 1;
190 :     }
191 :     }
192 :    
193 :     return 0;
194 :     }
195 :    
196 : sh002i 469 ################################################################################
197 :     # Macros used by content generators to render common idioms
198 :     ################################################################################
199 :    
200 :     # pathMacro(HASHREF, LIST) - helper macro for <!--#path--> escape: the hash
201 :     # reference contains the "style", "image", and "text" arguments to the escape.
202 :     # The LIST consists of ordered key-value pairs of the form:
203 :     #
204 :     # "Page Name" => URL
205 :     #
206 :     # If the page should not have a link associated with it, the URL should be left
207 :     # empty. Authentication data is added to the URL so you don't have to. A fully-
208 :     # formed path line is returned, suitable for returning by a function
209 :     # implementing the #path escape.
210 :     #
211 :     sub pathMacro {
212 : malsyned 323 my $self = shift;
213 : sh002i 469 my %args = %{ shift() };
214 :     my @path = @_;
215 :     my $sep;
216 :     if ($args{style} eq "image") {
217 :     $sep = CGI::img({-src=>$args{image}, -alt=>$args{text}});
218 :     } else {
219 :     $sep = $args{text};
220 :     }
221 :     my $auth = $self->url_authen_args;
222 :     my @result;
223 :     while (@path) {
224 :     my $name = shift @path;
225 :     my $url = shift @path;
226 :     push @result, $url
227 :     ? CGI::a({-href=>"$url?$auth"}, $name)
228 :     : $name;
229 :     }
230 : gage 1024 return join($sep, @result) . "\n";
231 : sh002i 469 }
232 :    
233 :     sub siblingsMacro {
234 :     my $self = shift;
235 :     my @siblings = @_;
236 :     my $sep = CGI::br();
237 :     my $auth = $self->url_authen_args;
238 :     my @result;
239 :     while (@siblings) {
240 :     my $name = shift @siblings;
241 :     my $url = shift @siblings;
242 :     push @result, $url
243 :     ? CGI::a({-href=>"$url?$auth"}, $name)
244 :     : $name;
245 :     }
246 :     return join($sep, @result), "\n";
247 :     }
248 :    
249 :     sub navMacro {
250 :     my $self = shift;
251 :     my %args = %{ shift() };
252 : sh002i 692 my $tail = shift;
253 : sh002i 469 my @links = @_;
254 :     my $auth = $self->url_authen_args;
255 : sh002i 809 my $ce = $self->{ce};
256 : malsyned 795 my $prefix = $ce->{webworkURLs}->{htdocs}."/images";
257 : sh002i 469 my @result;
258 :     while (@links) {
259 :     my $name = shift @links;
260 :     my $url = shift @links;
261 : malsyned 757 my $img = shift @links;
262 : malsyned 795 my $html =
263 :     ($img && $args{style} eq "images")
264 :     ? CGI::img(
265 :     {src=>($prefix."/".$img.$args{imagesuffix}),
266 :     border=>"",
267 :     alt=>"$name"})
268 :     : $name;
269 : malsyned 757 unless($img && !$url) {
270 :     push @result, $url
271 :     ? CGI::a({-href=>"$url?$auth$tail"}, $html)
272 :     : $html;
273 :     }
274 : sh002i 469 }
275 : gage 1024 return join($args{separator}, @result) . "\n";
276 : sh002i 469 }
277 :    
278 :     # hidden_fields(LIST) - return hidden <INPUT> tags for each field mentioned in
279 :     # LIST (or all fields if list is empty), taking data from the current request.
280 :     #
281 :     sub hidden_fields($;@) {
282 :     my $self = shift;
283 : malsyned 323 my $r = $self->{r};
284 : sh002i 469 my @fields = @_;
285 :     @fields or @fields = $r->param;
286 : sh002i 809 my $courseEnvironment = $self->{ce};
287 : malsyned 323 my $html = "";
288 :    
289 : sh002i 469 foreach my $param (@fields) {
290 : malsyned 323 my $value = $r->param($param);
291 : malsyned 447 $html .= CGI::input({-type=>"hidden",-name=>"$param",-value=>"$value"});
292 : malsyned 323 }
293 :     return $html;
294 :     }
295 :    
296 : sh002i 469 # hidden_authen_fields() - use hidden_fields to return hidden <INPUT> tags for
297 :     # request fields used in authentication.
298 :     #
299 :     sub hidden_authen_fields($) {
300 :     my $self = shift;
301 :     return $self->hidden_fields("user","effectiveUser","key");
302 :     }
303 : sh002i 425
304 : sh002i 469 # url_args(LIST) - return a URL query string (without the leading `?')
305 :     # containing values for each field mentioned in LIST, or all fields if list is
306 :     # empty. Data is taken from the current request.
307 :     #
308 :     sub url_args($;@) {
309 : sh002i 425 my $self = shift;
310 :     my $r = $self->{r};
311 :     my @fields = @_;
312 :     @fields or @fields = $r->param;
313 : sh002i 809 my $courseEnvironment = $self->{ce};
314 : sh002i 425
315 : sh002i 469 my @pairs;
316 : malsyned 441 foreach my $param (@fields) {
317 : sh002i 469 my $value = $r->param($param) || "";
318 :     push @pairs, uri_escape($param) . "=" . uri_escape($value);
319 : sh002i 425 }
320 : sh002i 469
321 :     return join("&", @pairs);
322 : sh002i 425 }
323 :    
324 : sh002i 469 # url_authen_args() - use url_args to return a URL query string for request
325 :     # fields used in authentication.
326 :     #
327 :     sub url_authen_args($) {
328 :     my $self = shift;
329 :     my $r = $self->{r};
330 :     return $self->url_args("user","effectiveUser","key");
331 : malsyned 390 }
332 :    
333 : sh002i 469 # print_form_data(BEGIN, MIDDLE, END, OMIT) - return a string containing request
334 :     # fields not matched by OMIT, placing BEGIN before each field name, MIDDLE
335 :     # between each field and its value, and END after each value. Values are taken
336 :     # from the current request. OMIT is a quoted reguar expression.
337 :     #
338 :     sub print_form_data {
339 :     my ($self, $begin, $middle, $end, $qr_omit) = @_;
340 :     my $return_string = "";
341 :     my $r=$self->{r};
342 :     my @form_data = $r->param;
343 :     foreach my $name (@form_data) {
344 :     next if ($qr_omit and $name =~ /$qr_omit/);
345 :     my @values = $r->param($name);
346 :     foreach my $variable (qw(begin name middle value end)) {
347 :     no strict 'refs';
348 :     ${$variable} = "" unless defined ${$variable};
349 :     }
350 :     foreach my $value (@values) {
351 :     $return_string .= "$begin$name$middle$value$end";
352 :     }
353 :     }
354 :     return $return_string;
355 : malsyned 390 }
356 :    
357 : sh002i 737 sub errorOutput($$$) {
358 :     my ($self, $error, $details) = @_;
359 :     return
360 : gage 1152 CGI::h3("Software Error"),
361 : sh002i 737 CGI::p(<<EOF),
362 : sh002i 1131 WeBWorK has encountered a software error while attempting to process this
363 :     problem. It is likely that there is an error in the problem itself. If you are
364 :     a student, contact your professor to have the error corrected. If you are a
365 :     professor, please consut the error output below for more informaiton.
366 : sh002i 737 EOF
367 : sh002i 1142 CGI::h3("Error messages"), CGI::p(CGI::tt($error)),
368 :     CGI::h3("Error context"), CGI::p(CGI::tt($details));
369 : sh002i 737 }
370 :    
371 :     sub warningOutput($$) {
372 :     my ($self, $warnings) = @_;
373 :    
374 : sh002i 1169 my @warnings = split m/\n+/, $warnings;
375 :    
376 : sh002i 737 return
377 : gage 1152 CGI::h3("Software Warnings"),
378 : sh002i 737 CGI::p(<<EOF),
379 : sh002i 1131 WeBWorK has encountered warnings while attempting to process this problem. It
380 :     is likely that this indicates an error or ambiguity in the problem itself. If
381 :     you are a student, contact your professor to have the problem corrected. If you
382 : sh002i 1142 are a professor, please consut the warning output below for more informaiton.
383 : sh002i 737 EOF
384 :     CGI::h3("Warning messages"),
385 : sh002i 1169 CGI::ul(CGI::li(\@warnings)),
386 : sh002i 737 ;
387 :     }
388 :    
389 : sh002i 469 ################################################################################
390 :     # Generic versions of template escapes
391 :     ################################################################################
392 : malsyned 390
393 : sh002i 469 # Reminder: here are the template functions currently defined:
394 : sh002i 1131 # FIXME: this list is out of date!!!!!!!!
395 : sh002i 469 #
396 : sh002i 555 # head
397 : sh002i 469 # path
398 :     # style = text|image
399 :     # image = URL of image
400 :     # text = text separator
401 : sh002i 675 # loginstatus
402 : sh002i 505 # links
403 : sh002i 469 # siblings
404 :     # nav
405 :     # style = text|image
406 :     # imageprefix = prefix to image URL
407 :     # imagesuffix = suffix to image URL
408 :     # separator = HTML to place in between links
409 :     # title
410 :     # body
411 : malsyned 313
412 : malsyned 349 sub header {
413 : malsyned 305 my $self = shift;
414 : sh002i 469 my $r = $self->{r};
415 : malsyned 349 $r->content_type('text/html');
416 :     $r->send_http_header();
417 :     }
418 :    
419 : sh002i 682 sub loginstatus {
420 :     my $self = shift;
421 :     my $r = $self->{r};
422 :     my $user = $r->param("user");
423 :     my $eUser = $r->param("effectiveUser");
424 :     my $key = $r->param("key");
425 :     return "" unless $key;
426 : sh002i 692 my $exitURL = $r->uri() . "?user=$user&key=$key";
427 : malsyned 765 print CGI::small("User:", "$user");
428 : sh002i 682 if ($user ne $eUser) {
429 : sh002i 692 print CGI::br(), CGI::font({-color=>'red'},
430 : malsyned 765 CGI::small("Acting as:", "$eUser")
431 : sh002i 692 ),
432 :     CGI::br(), CGI::a({-href=>$exitURL},
433 :     CGI::small("Stop Acting")
434 :     );
435 : sh002i 682 }
436 :     return "";
437 :     }
438 :    
439 : sh002i 1131 # FIXME: drunk code. rewrite.
440 : sh002i 667 # also, this should be structured s.t. subclasses can add items to the links
441 :     # area, i.e. "stacking"
442 : sh002i 505 sub links {
443 : malsyned 353 my $self = shift;
444 : sh002i 809 my $ce = $self->{ce};
445 : sh002i 817 my $db = $self->{db};
446 : sh002i 526 my $userName = $self->{r}->param("user");
447 :     my $courseName = $ce->{courseName};
448 : sh002i 469 my $root = $ce->{webworkURLs}->{root};
449 : sh002i 817 my $permLevel = $db->getPermissionLevel($userName)->permission();
450 :     my $key = $db->getKey($userName)->key();
451 : sh002i 646 return "" unless defined $key;
452 : sh002i 526
453 : sh002i 667 # URLs to parts of the system
454 : malsyned 836 my $probSets = "$root/$courseName/?" . $self->url_authen_args();
455 :     my $prefs = "$root/$courseName/options/?" . $self->url_authen_args();
456 :     my $instructor = "$root/$courseName/instructor/?" . $self->url_authen_args();
457 :     my $help = "$ce->{webworkURLs}->{docs}?" . $self->url_authen_args();
458 :     my $logout = "$root/$courseName/logout/?" . $self->url_authen_args();
459 : sh002i 526
460 : sh002i 476 return
461 : gage 833 CGI::a({-href=>$probSets}, "Problem Sets"). CGI::br().
462 :     CGI::a({-href=>$prefs}, "User Options"). CGI::br().
463 : sh002i 667 ($permLevel > 0
464 : malsyned 836 ? CGI::a({-href=>$instructor}, "Instructor") . CGI::br()
465 : gage 833 : "").
466 :     CGI::a({-href=>$help}, "Help"). CGI::br().
467 :     CGI::a({-href=>$logout}, "Log Out"). CGI::br()
468 : sh002i 476 ;
469 : malsyned 353 }
470 :    
471 : malsyned 525 # &if_can will return 1 if the current object->can("do $_[1]")
472 :     sub if_can ($$) {
473 :     my ($self, $arg) = (@_);
474 :    
475 :     if ($self->can("$arg")) {
476 :     return 1;
477 :     } else {
478 :     return 0;
479 :     }
480 :     }
481 :    
482 : malsyned 748 # Every content generator is logged in unless it says otherwise.
483 :     sub if_loggedin($$) {
484 :     my ($self, $arg) = (@_);
485 :    
486 :     return $arg;
487 :     }
488 :    
489 : sh002i 1131 # Handling of errors in submissions
490 :    
491 : malsyned 1017 sub if_submiterror($$) {
492 :     my ($self, $arg) = @_;
493 :     if (exists $self->{submitError}) {
494 :     return $arg;
495 :     } else {
496 :     return !$arg;
497 :     }
498 :     }
499 :    
500 : sh002i 1131 sub submiterror {
501 :     my ($self) = @_;
502 :     if (exists $self->{submitError}) {
503 :     return $self->{submitError};
504 :     } else {
505 :     return "";
506 :     }
507 :     }
508 :    
509 :     # General warning handling
510 :    
511 :     sub if_warnings($$) {
512 :     my ($self, $arg) = @_;
513 :     return $self->{r}->notes("warnings") ? $arg : !$arg;
514 :     }
515 :    
516 :     sub warnings {
517 :     my ($self) = @_;
518 :     my $r = $self->{r};
519 :     if ($r->notes("warnings")) {
520 :     return $self->warningOutput($r->notes("warnings"));
521 :     } else {
522 :     return "";
523 :     }
524 :     }
525 :    
526 : malsyned 313 1;
527 : malsyned 508
528 :     __END__
529 :    
530 :     =head1 AUTHOR
531 :    
532 :     Written by Dennis Lambe Jr., malsyned (at) math.rochester.edu
533 :     and Sam Hathaway, sh002i (at) math.rochester.edu.
534 :    
535 :     =cut

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9