[system] / trunk / webwork-modperl / lib / WeBWorK / ContentGenerator.pm Repository:
ViewVC logotype

Annotation of /trunk/webwork-modperl/lib/WeBWorK/ContentGenerator.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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 526 use WeBWorK::DB::Auth;
20 : sh002i 476 use WeBWorK::Utils qw(readFile);
21 : malsyned 403 #use CGI::Carp qw(fatalsToBrowser);
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 469 # new(Apache::Request, WeBWorK::CourseEnvironment) - create a new instance of a
29 :     # 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 :     #
34 :     # WeBWorK::ContentGenerator::WHATEVER->new($r, $ce)->go(@whatever);
35 :     #
36 :     # and throws away the result ;)
37 :     #
38 : malsyned 305 sub new($$$) {
39 : malsyned 323 my $invocant = shift;
40 :     my $class = ref($invocant) || $invocant;
41 : malsyned 305 my $self = {};
42 :     ($self->{r}, $self->{courseEnvironment}) = @_;
43 :     bless $self, $class;
44 :     return $self;
45 :     }
46 :    
47 : sh002i 469 ################################################################################
48 :     # Invocation and template processing
49 :     ################################################################################
50 : malsyned 323
51 : sh002i 469 # go(@otherArguments) - render a page, using methods from the particular
52 :     # subclass of ContentGenerator. @otherArguments is passed to each method, so
53 :     # that the dispatcher can pass CG-specific data. The order of calls looks like
54 :     # this:
55 :     #
56 :     # * &pre_header_initialize - give subclasses a chance to do initialization
57 :     # necessary for generating the HTTP header.
58 :     # * &header - this class provides a standard HTTP header with Content-Type
59 :     # text/html. Subclasses are welcome to overload this for things like
60 :     # an image-creation content generator or a PDF generator.
61 :     # * &initialize - let subclasses do post-header initialization.
62 :     # * any "template escapes" defined in the system template and supported by
63 :     # the subclass. Generic implementations of &title and &body are provided.
64 :     #
65 :     sub go {
66 :     my $self = shift;
67 :     my $r = $self->{r};
68 :     my $courseEnvironment = $self->{courseEnvironment};
69 :    
70 :     $self->pre_header_initialize(@_) if $self->can("pre_header_initialize");
71 :     $self->header(@_);
72 :     return OK if $r->header_only;
73 : malsyned 313
74 : sh002i 469 $self->initialize(@_) if $self->can("initialize");
75 :     $self->template($courseEnvironment->{templates}->{system}, @_);
76 : malsyned 441
77 : sh002i 469 return OK;
78 :     }
79 :    
80 :     # template(STRING, @otherArguments) - parse a template, looking for escapes of
81 :     # the form <!--#NAME ARG1="FOO" ARG2="BAR"--> and calling a member function NAME
82 :     # (if available) for each NAME. The escapes are called like:
83 :     #
84 :     # $self->NAME(@otherArguments, \%escapeArguments)
85 :     #
86 :     # where @otherArguments originates in the dispatcher and %escapeArguments is
87 :     # parsed out of the escape itself (i.e. ARG1 => FOO, ARG2 => BAR)
88 :     #
89 :     sub template {
90 :     my ($self, $templateFile) = (shift, shift);
91 :     my $r = $self->{r};
92 :     my $courseEnvironment = $self->{courseEnvironment};
93 : malsyned 512 my @ifstack = (1); # Start off in printing mode
94 :     # say $ifstack[-1] to get the result of the last <#!--if-->
95 : sh002i 469
96 : sh002i 476 # so even though the variable $/ APPEARS to contain a newline,
97 :     # <TEMPLATE> is slurping the whole file into the first element of
98 :     # @template ONLY AFTER THE TRANSLATOR RUNS. WTF!!!
99 :     #
100 :     #open(TEMPLATE, $templateFile) or die "Couldn't open template $templateFile";
101 :     #my @template = <TEMPLATE>;
102 :     #close TEMPLATE;
103 :     #
104 :     # Let's try something else instead:
105 :     my @template = split /\n/, readFile($templateFile);
106 :    
107 : sh002i 469 foreach my $line (@template) {
108 : sh002i 476 #warn "foo: $line\n";
109 : sh002i 469 # This is incremental regex processing.
110 :     # the /c is so that pos($line) doesn't die when the regex fails.
111 :     while ($line =~ m/\G(.*?)<!--#(\w*)((?:\s+.*?)?)-->/gc) {
112 :     my ($before, $function, $raw_args) = ($1, $2, $3);
113 :     # $args here will be a hashref
114 : malsyned 512 my @args = $raw_args =~ /\S/ ? cook_args($raw_args) : {};
115 :     if ($ifstack[-1]) {
116 :     print $before;
117 :     }
118 :    
119 : sh002i 476 if ($self->can($function)) {
120 : malsyned 512 if ($function eq "if") {
121 :     push @ifstack, $self->$function(@_, [@args]);
122 :     } elsif ($function eq "else" and @ifstack > 1) {
123 :     $ifstack[-1] = not $ifstack[-1];
124 :     } elsif ($function eq "endif" and @ifstack > 1) {
125 : malsyned 522 pop @ifstack;
126 : malsyned 512 } elsif ($ifstack[-1]) {
127 :     print $self->$function(@_, {@args});
128 :     }
129 : sh002i 476 }
130 : malsyned 313 }
131 : sh002i 469
132 : malsyned 512 if ($ifstack[-1]) {
133 : malsyned 522 print substr $line, (defined pos $line) ? pos $line : 0;
134 : malsyned 512 }
135 : malsyned 313 }
136 : sh002i 469 }
137 :    
138 :     # cook_args(STRING) - parses a string of the form ARG1="FOO" ARG2="BAR". Returns
139 : malsyned 512 # a list which pairs into key/values and fits nicely in {}s.
140 : sh002i 469 #
141 :     sub cook_args($) {
142 :     my ($raw_args) = @_;
143 : malsyned 512 my @args = ();
144 : malsyned 353
145 : malsyned 508 # Boy I love m//g in scalar context! Go read the camel book, heathen.
146 :     # First, get the whole token with the quotes on both ends...
147 :     while ($raw_args =~ m/\G\s*(\w*)="((?:[^"\\]|\\.)*)"/g) {
148 :     my ($key, $value) = ($1, $2);
149 :     # ... then, rip out all the protecty backspaces
150 : malsyned 522 $value =~ s/\\(.)/$1/g;
151 : malsyned 512 push @args, $key => $value;
152 : sh002i 469 }
153 :    
154 : malsyned 512 return @args;
155 : malsyned 313 }
156 :    
157 : sh002i 469 ################################################################################
158 :     # Macros used by content generators to render common idioms
159 :     ################################################################################
160 :    
161 :     # pathMacro(HASHREF, LIST) - helper macro for <!--#path--> escape: the hash
162 :     # reference contains the "style", "image", and "text" arguments to the escape.
163 :     # The LIST consists of ordered key-value pairs of the form:
164 :     #
165 :     # "Page Name" => URL
166 :     #
167 :     # If the page should not have a link associated with it, the URL should be left
168 :     # empty. Authentication data is added to the URL so you don't have to. A fully-
169 :     # formed path line is returned, suitable for returning by a function
170 :     # implementing the #path escape.
171 :     #
172 :     sub pathMacro {
173 : malsyned 323 my $self = shift;
174 : sh002i 469 my %args = %{ shift() };
175 :     my @path = @_;
176 :     my $sep;
177 :     if ($args{style} eq "image") {
178 :     $sep = CGI::img({-src=>$args{image}, -alt=>$args{text}});
179 :     } else {
180 :     $sep = $args{text};
181 :     }
182 :     my $auth = $self->url_authen_args;
183 :     my @result;
184 :     while (@path) {
185 :     my $name = shift @path;
186 :     my $url = shift @path;
187 :     push @result, $url
188 :     ? CGI::a({-href=>"$url?$auth"}, $name)
189 :     : $name;
190 :     }
191 :     return join($sep, @result), "\n";
192 :     }
193 :    
194 :     sub siblingsMacro {
195 :     my $self = shift;
196 :     my @siblings = @_;
197 :     my $sep = CGI::br();
198 :     my $auth = $self->url_authen_args;
199 :     my @result;
200 :     while (@siblings) {
201 :     my $name = shift @siblings;
202 :     my $url = shift @siblings;
203 :     push @result, $url
204 :     ? CGI::a({-href=>"$url?$auth"}, $name)
205 :     : $name;
206 :     }
207 :     return join($sep, @result), "\n";
208 :     }
209 :    
210 :     sub navMacro {
211 :     my $self = shift;
212 :     my %args = %{ shift() };
213 :     my @links = @_;
214 :     my $auth = $self->url_authen_args;
215 :     my @result;
216 :     while (@links) {
217 :     my $name = shift @links;
218 :     my $url = shift @links;
219 :     push @result, $url
220 :     ? CGI::a({-href=>"$url?$auth"}, $name)
221 :     : $name;
222 :     }
223 :     return join($args{separator}, @result), "\n";
224 :     }
225 :    
226 :     # hidden_fields(LIST) - return hidden <INPUT> tags for each field mentioned in
227 :     # LIST (or all fields if list is empty), taking data from the current request.
228 :     #
229 :     sub hidden_fields($;@) {
230 :     my $self = shift;
231 : malsyned 323 my $r = $self->{r};
232 : sh002i 469 my @fields = @_;
233 :     @fields or @fields = $r->param;
234 : malsyned 323 my $courseEnvironment = $self->{courseEnvironment};
235 :     my $html = "";
236 :    
237 : sh002i 469 foreach my $param (@fields) {
238 : malsyned 323 my $value = $r->param($param);
239 : malsyned 447 $html .= CGI::input({-type=>"hidden",-name=>"$param",-value=>"$value"});
240 : malsyned 323 }
241 :     return $html;
242 :     }
243 :    
244 : sh002i 469 # hidden_authen_fields() - use hidden_fields to return hidden <INPUT> tags for
245 :     # request fields used in authentication.
246 :     #
247 :     sub hidden_authen_fields($) {
248 :     my $self = shift;
249 :     return $self->hidden_fields("user","effectiveUser","key");
250 :     }
251 : sh002i 425
252 : sh002i 469 # url_args(LIST) - return a URL query string (without the leading `?')
253 :     # containing values for each field mentioned in LIST, or all fields if list is
254 :     # empty. Data is taken from the current request.
255 :     #
256 :     sub url_args($;@) {
257 : sh002i 425 my $self = shift;
258 :     my $r = $self->{r};
259 :     my @fields = @_;
260 :     @fields or @fields = $r->param;
261 :     my $courseEnvironment = $self->{courseEnvironment};
262 :    
263 : sh002i 469 my @pairs;
264 : malsyned 441 foreach my $param (@fields) {
265 : sh002i 469 my $value = $r->param($param) || "";
266 :     push @pairs, uri_escape($param) . "=" . uri_escape($value);
267 : sh002i 425 }
268 : sh002i 469
269 :     return join("&", @pairs);
270 : sh002i 425 }
271 :    
272 : sh002i 469 # url_authen_args() - use url_args to return a URL query string for request
273 :     # fields used in authentication.
274 :     #
275 :     sub url_authen_args($) {
276 :     my $self = shift;
277 :     my $r = $self->{r};
278 :     return $self->url_args("user","effectiveUser","key");
279 : malsyned 390 }
280 :    
281 : sh002i 469 # print_form_data(BEGIN, MIDDLE, END, OMIT) - return a string containing request
282 :     # fields not matched by OMIT, placing BEGIN before each field name, MIDDLE
283 :     # between each field and its value, and END after each value. Values are taken
284 :     # from the current request. OMIT is a quoted reguar expression.
285 :     #
286 :     sub print_form_data {
287 :     my ($self, $begin, $middle, $end, $qr_omit) = @_;
288 :     my $return_string = "";
289 :     my $r=$self->{r};
290 :     my @form_data = $r->param;
291 :     foreach my $name (@form_data) {
292 :     next if ($qr_omit and $name =~ /$qr_omit/);
293 :     my @values = $r->param($name);
294 :     foreach my $variable (qw(begin name middle value end)) {
295 :     no strict 'refs';
296 :     ${$variable} = "" unless defined ${$variable};
297 :     }
298 :     foreach my $value (@values) {
299 :     $return_string .= "$begin$name$middle$value$end";
300 :     }
301 :     }
302 :     return $return_string;
303 : malsyned 390 }
304 :    
305 : sh002i 469 ################################################################################
306 :     # Generic versions of template escapes
307 :     ################################################################################
308 : malsyned 390
309 : sh002i 469 # Reminder: here are the template functions currently defined:
310 :     #
311 :     # path
312 :     # style = text|image
313 :     # image = URL of image
314 :     # text = text separator
315 : sh002i 505 # links
316 : sh002i 469 # siblings
317 :     # nav
318 :     # style = text|image
319 :     # imageprefix = prefix to image URL
320 :     # imagesuffix = suffix to image URL
321 :     # separator = HTML to place in between links
322 :     # title
323 :     # body
324 : malsyned 313
325 : malsyned 349 sub header {
326 : malsyned 305 my $self = shift;
327 : sh002i 469 my $r = $self->{r};
328 : malsyned 349 $r->content_type('text/html');
329 :     $r->send_http_header();
330 :     }
331 :    
332 : sh002i 526 # drunk code. rewrite.
333 : sh002i 505 sub links {
334 : malsyned 353 my $self = shift;
335 : sh002i 469 my $ce = $self->{courseEnvironment};
336 : sh002i 526 my $userName = $self->{r}->param("user");
337 :     my $courseName = $ce->{courseName};
338 : sh002i 469 my $root = $ce->{webworkURLs}->{root};
339 : sh002i 526 my $permLevel = WeBWorK::DB::Auth->new($ce)->getPermissions($userName);
340 :    
341 : sh002i 469 my $probSets = "$root/$courseName/?" . $self->url_authen_args();
342 : sh002i 526 my $prefs = "$root/$courseName/prefs/?" . $self->url_authen_args();
343 :     my $prof = "$root/$courseName/prof/?" . $self->url_authen_args();
344 :     my $profLine;
345 :     if ($permLevel > 0) {
346 :     $profLine = CGI::a({-href=>$prof}, "Professor") . CGI::br(),
347 :     }
348 :     my $help = $ce->{webworkURLs}->{docs} . "?" . $self->url_authen_args();
349 :     my $logout = "$root/$courseName/?user=$userName";
350 :    
351 : sh002i 476 return
352 : sh002i 469 CGI::a({-href=>$probSets}, "Problem Sets"), CGI::br(),
353 : sh002i 526 CGI::a({-href=>$prefs}, "User Options"), CGI::br(),
354 :     $profLine,
355 :     CGI::a({-href=>$help}, "Help"), CGI::br(),
356 : sh002i 476 CGI::a({-href=>$logout}, "Log Out"), CGI::br(),
357 :     ;
358 : malsyned 353 }
359 :    
360 : malsyned 512 # This is different. It probably should print anything (except in debugging cases)
361 :     # and it should return a boolean, not a string. &if is called in a nonstandard way
362 :     # by &template, with $args as an arrayref instead of a hashref. this is a hack! yay!
363 : malsyned 525
364 :     # OK, this is a pluggin architecture. it iterates through attributes of the "if" tag,
365 :     # and for each predicate $p, it calls &if_$p in an object-oriented way, continuing the
366 :     # grand templating theme of an object-oriented pluggable architecture using ->can($).
367 : malsyned 512 sub if {
368 :     my ($self, $args) = @_[0,-1];
369 :     # A single if "or"s it's components. Nesting produces "and".
370 :    
371 :     my @args = @$args; # Hahahahaha, get it?!
372 :    
373 :     if (@args % 2 != 0) {
374 :     # flip out and kill people, but do not commit seppuku
375 :     print '<!--&if recieved an uneven number of arguments. This shouldn\'t happen, but I\'ll let it slide.-->\n';
376 :     }
377 :    
378 :     while (@args > 1) {
379 :     my ($key, $value) = (shift @args, shift @args);
380 :    
381 : malsyned 525 # a non-existent &if_$key is the same as a false result, but we're ORing, so it's OK
382 :     my $sub = "if_$key"; # perl doesn't like it when you try to construct a string right in a method invocation
383 :     if ($self->can("if_$key") and $self->$sub("$value")) {
384 : malsyned 512 return 1;
385 :     }
386 :     }
387 :    
388 :     return 0;
389 : malsyned 390 }
390 :    
391 : malsyned 525 # &if_can will return 1 if the current object->can("do $_[1]")
392 :     sub if_can ($$) {
393 :     my ($self, $arg) = (@_);
394 :    
395 :     if ($self->can("$arg")) {
396 :     return 1;
397 :     } else {
398 :     return 0;
399 :     }
400 :     }
401 :    
402 : malsyned 313 1;
403 : malsyned 508
404 :     __END__
405 :    
406 :     =head1 AUTHOR
407 :    
408 :     Written by Dennis Lambe Jr., malsyned (at) math.rochester.edu
409 :     and Sam Hathaway, sh002i (at) math.rochester.edu.
410 :    
411 :     =cut

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9