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