Annotation of loncom/interface/lonhelper.pm, revision 1.28
1.1 bowersj2 1: # The LearningOnline Network with CAPA
2: # .helper XML handler to implement the LON-CAPA helper
3: #
1.26 bowersj2 4: # $Id: lonhelper.pm,v 1.25 2003/05/08 19:52:43 bowersj2 Exp $
1.1 bowersj2 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: # (Page Handler
29: #
30: # (.helper handler
31: #
32:
1.3 bowersj2 33: =pod
34:
35: =head1 lonhelper - HTML Helper framework for LON-CAPA
36:
37: Helpers, often known as "wizards", are well-established UI widgets that users
38: feel comfortable with. It can take a complicated multidimensional problem the
39: user has and turn it into a series of bite-sized one-dimensional questions.
40:
41: For developers, helpers provide an easy way to bundle little bits of functionality
42: for the user, without having to write the tedious state-maintenence code.
43:
44: Helpers are defined as XML documents, placed in the /home/httpd/html/adm/helpers
45: directory and having the .helper file extension. For examples, see that directory.
46:
47: All classes are in the Apache::lonhelper namespace.
48:
49: =head2 lonhelper XML file format
50:
51: A helper consists of a top-level <helper> tag which contains a series of states.
52: Each state contains one or more state elements, which are what the user sees, like
53: messages, resource selections, or date queries.
54:
55: The helper tag is required to have one attribute, "title", which is the name
56: of the helper itself, such as "Parameter helper".
57:
58: =head2 State tags
59:
60: State tags are required to have an attribute "name", which is the symbolic
1.7 bowersj2 61: name of the state and will not be directly seen by the user. The helper is
62: required to have one state named "START", which is the state the helper
1.5 bowersj2 63: will start with. By convention, this state should clearly describe what
1.3 bowersj2 64: the helper will do for the user, and may also include the first information
65: entry the user needs to do for the helper.
66:
67: State tags are also required to have an attribute "title", which is the
68: human name of the state, and will be displayed as the header on top of
69: the screen for the user.
70:
71: =head2 Example Helper Skeleton
72:
73: An example of the tags so far:
74:
75: <helper title="Example Helper">
76: <state name="START" title="Demonstrating the Example Helper">
77: <!-- notice this is the START state the wizard requires -->
78: </state>
79: <state name="GET_NAME" title="Enter Student Name">
80: </state>
81: </helper>
82:
83: Of course this does nothing. In order for the wizard to do something, it is
84: necessary to put actual elements into the wizard. Documentation for each
85: of these elements follows.
86:
1.13 bowersj2 87: =head2 Creating a Helper With Code, Not XML
88:
89: In some situations, such as the printing wizard (see lonprintout.pm),
90: writing the helper in XML would be too complicated, because of scope
91: issues or the fact that the code actually outweighs the XML. It is
92: possible to create a helper via code, though it is a little odd.
93:
94: Creating a helper via code is more like issuing commands to create
95: a helper then normal code writing. For instance, elements will automatically
96: be added to the last state created, so it's important to create the
97: states in the correct order.
98:
99: First, create a new helper:
100:
101: use Apache::lonhelper;
102:
103: my $helper = Apache::lonhelper::new->("Helper Title");
104:
105: Next you'll need to manually add states to the helper:
106:
107: Apache::lonhelper::state->new("STATE_NAME", "State's Human Title");
108:
109: You don't need to save a reference to it because all elements up until
110: the next state creation will automatically be added to this state.
111:
112: Elements are created by populating the $paramHash in
113: Apache::lonhelper::paramhash. To prevent namespace issues, retrieve
114: a reference to that has with getParamHash:
115:
116: my $paramHash = Apache::lonhelper::getParamHash();
117:
118: You will need to do this for each state you create.
119:
120: Populate the $paramHash with the parameters for the element you wish
121: to add next; the easiest way to find out what those entries are is
122: to read the code. Some common ones are 'variable' to record the variable
123: to store the results in, and NEXTSTATE to record a next state transition.
124:
125: Then create your element:
126:
127: $paramHash->{MESSAGETEXT} = "This is a message.";
128: Apache::lonhelper::message->new();
129:
130: The creation will take the $paramHash and bless it into a
131: Apache::lonhelper::message object. To create the next element, you need
132: to get a reference to the new, empty $paramHash:
133:
134: $paramHash = Apache::lonhelper::getParamHash();
135:
136: and you can repeat creating elements that way. You can add states
137: and elements as needed.
138:
139: See lonprintout.pm, subroutine printHelper for an example of this, where
140: we dynamically add some states to prevent security problems, for instance.
141:
142: Normally the machinery in the XML format is sufficient; dynamically
143: adding states can easily be done by wrapping the state in a <condition>
144: tag. This should only be used when the code dominates the XML content,
145: the code is so complicated that it is difficult to get access to
146: all of the information you need because of scoping issues, or so much
147: of the information used is persistent because would-be <exec> or
148: <eval> blocks that using the {DATA} mechanism results in hard-to-read
149: and -maintain code.
150:
151: It is possible to do some of the work with an XML fragment parsed by
1.17 bowersj2 152: lonxml; again, see lonprintout.pm for an example. In that case it is
153: imperative that you call B<Apache::lonhelper::registerHelperTags()>
154: before parsing XML fragments and B<Apache::lonhelper::unregisterHelperTags()>
155: when you are done. See lonprintout.pm for examples of this usage in the
156: printHelper subroutine.
1.13 bowersj2 157:
1.3 bowersj2 158: =cut
159:
1.1 bowersj2 160: package Apache::lonhelper;
1.2 bowersj2 161: use Apache::Constants qw(:common);
162: use Apache::File;
1.3 bowersj2 163: use Apache::lonxml;
1.2 bowersj2 164:
1.7 bowersj2 165: # Register all the tags with the helper, so the helper can
166: # push and pop them
167:
168: my @helperTags;
169:
170: sub register {
171: my ($namespace, @tags) = @_;
172:
173: for my $tag (@tags) {
174: push @helperTags, [$namespace, $tag];
175: }
176: }
177:
1.2 bowersj2 178: BEGIN {
1.7 bowersj2 179: Apache::lonxml::register('Apache::lonhelper',
180: ('helper'));
181: register('Apache::lonhelper', ('state'));
1.2 bowersj2 182: }
183:
1.7 bowersj2 184: # Since all helpers are only three levels deep (helper tag, state tag,
1.3 bowersj2 185: # substate type), it's easier and more readble to explicitly track
186: # those three things directly, rather then futz with the tag stack
187: # every time.
188: my $helper;
189: my $state;
190: my $substate;
1.4 bowersj2 191: # To collect parameters, the contents of the subtags are collected
192: # into this paramHash, then passed to the element object when the
193: # end of the element tag is located.
194: my $paramHash;
1.2 bowersj2 195:
1.25 bowersj2 196: # Note from Jeremy 5-8-2003: It is *vital* that the real handler be called
197: # as a subroutine from the handler, or very mysterious things might happen.
198: # I don't know exactly why, but it seems that the scope where the Apache
199: # server enters the perl handler is treated differently from the rest of
200: # the handler. This also seems to manifest itself in the debugger as entering
201: # the perl handler in seemingly random places (sometimes it starts in the
202: # compiling phase, sometimes in the handler execution phase where it runs
203: # the code and stepping into the "1;" the module ends with goes into the handler,
204: # sometimes starting directly with the handler); I think the cause is related.
205: # In the debugger, this means that breakpoints are ignored until you step into
206: # a function and get out of what must be a "faked up scope" in the Apache->
207: # mod_perl connection. In this code, it was manifesting itself in the existence
208: # of two seperate file-scoped $helper variables, one set to the value of the
209: # helper in the helper constructor, and one referenced by the handler on the
210: # "$helper->process()" line. The second was therefore never set, and was still
211: # undefined when I tried to call process on it.
212: # By pushing the "real handler" down into the "real scope", everybody except the
213: # actual handler function directly below this comment gets the same $helper and
214: # everybody is happy.
215: # The upshot of all of this is that for safety when a handler is using
216: # file-scoped variables in LON-CAPA, the handler should be pushed down one
217: # call level, as I do here, to ensure that the top-level handler function does
218: # not get a different file scope from the rest of the code.
219: sub handler {
220: my $r = shift;
221: return real_handler($r);
222: }
223:
1.13 bowersj2 224: # For debugging purposes, one can send a second parameter into this
225: # function, the 'uri' of the helper you wish to have rendered, and
226: # call this from other handlers.
1.25 bowersj2 227: sub real_handler {
1.3 bowersj2 228: my $r = shift;
1.13 bowersj2 229: my $uri = shift;
230: if (!defined($uri)) { $uri = $r->uri(); }
231: $ENV{'request.uri'} = $uri;
232: my $filename = '/home/httpd/html' . $uri;
1.2 bowersj2 233: my $fh = Apache::File->new($filename);
234: my $file;
1.3 bowersj2 235: read $fh, $file, 100000000;
236:
1.27 bowersj2 237:
1.3 bowersj2 238: # Send header, don't cache this page
239: if ($r->header_only) {
240: if ($ENV{'browser.mathml'}) {
241: $r->content_type('text/xml');
242: } else {
243: $r->content_type('text/html');
244: }
245: $r->send_http_header;
246: return OK;
247: }
248: if ($ENV{'browser.mathml'}) {
249: $r->content_type('text/xml');
250: } else {
251: $r->content_type('text/html');
252: }
253: $r->send_http_header;
254: $r->rflush();
1.2 bowersj2 255:
1.3 bowersj2 256: # Discard result, we just want the objects that get created by the
257: # xml parsing
258: &Apache::lonxml::xmlparse($r, 'helper', $file);
1.2 bowersj2 259:
1.13 bowersj2 260: $helper->process();
261:
1.3 bowersj2 262: $r->print($helper->display());
1.7 bowersj2 263: return OK;
1.2 bowersj2 264: }
265:
1.13 bowersj2 266: sub registerHelperTags {
267: for my $tagList (@helperTags) {
268: Apache::lonxml::register($tagList->[0], $tagList->[1]);
269: }
270: }
271:
272: sub unregisterHelperTags {
273: for my $tagList (@helperTags) {
274: Apache::lonxml::deregister($tagList->[0], $tagList->[1]);
275: }
276: }
277:
1.2 bowersj2 278: sub start_helper {
279: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
280:
281: if ($target ne 'helper') {
282: return '';
283: }
1.7 bowersj2 284:
1.13 bowersj2 285: registerHelperTags();
286:
287: Apache::lonhelper::helper->new($token->[2]{'title'});
1.4 bowersj2 288: return '';
1.2 bowersj2 289: }
290:
291: sub end_helper {
292: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
293:
1.3 bowersj2 294: if ($target ne 'helper') {
295: return '';
296: }
1.7 bowersj2 297:
1.13 bowersj2 298: unregisterHelperTags();
1.7 bowersj2 299:
1.4 bowersj2 300: return '';
1.2 bowersj2 301: }
1.1 bowersj2 302:
1.3 bowersj2 303: sub start_state {
304: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
305:
306: if ($target ne 'helper') {
307: return '';
308: }
309:
1.13 bowersj2 310: Apache::lonhelper::state->new($token->[2]{'name'},
311: $token->[2]{'title'});
1.3 bowersj2 312: return '';
313: }
314:
1.13 bowersj2 315: # Use this to get the param hash from other files.
316: sub getParamHash {
317: return $paramHash;
318: }
319:
320: # Use this to get the helper, if implementing elements in other files
321: # (like lonprintout.pm)
322: sub getHelper {
323: return $helper;
324: }
325:
1.3 bowersj2 326: # don't need this, so ignore it
327: sub end_state {
328: return '';
329: }
330:
1.1 bowersj2 331: 1;
332:
1.3 bowersj2 333: package Apache::lonhelper::helper;
334:
335: use Digest::MD5 qw(md5_hex);
336: use HTML::Entities;
337: use Apache::loncommon;
338: use Apache::File;
339:
340: sub new {
341: my $proto = shift;
342: my $class = ref($proto) || $proto;
343: my $self = {};
344:
345: $self->{TITLE} = shift;
346:
347: # If there is a state from the previous form, use that. If there is no
348: # state, use the start state parameter.
349: if (defined $ENV{"form.CURRENT_STATE"})
350: {
351: $self->{STATE} = $ENV{"form.CURRENT_STATE"};
352: }
353: else
354: {
355: $self->{STATE} = "START";
356: }
357:
358: $self->{TOKEN} = $ENV{'form.TOKEN'};
359: # If a token was passed, we load that in. Otherwise, we need to create a
360: # new storage file
361: # Tried to use standard Tie'd hashes, but you can't seem to take a
362: # reference to a tied hash and write to it. I'd call that a wart.
363: if ($self->{TOKEN}) {
364: # Validate the token before trusting it
365: if ($self->{TOKEN} !~ /^[a-f0-9]{32}$/) {
366: # Not legit. Return nothing and let all hell break loose.
367: # User shouldn't be doing that!
368: return undef;
369: }
370:
371: # Get the hash.
372: $self->{FILENAME} = $Apache::lonnet::tmpdir . md5_hex($self->{TOKEN}); # Note the token is not the literal file
373:
374: my $file = Apache::File->new($self->{FILENAME});
375: my $contents = <$file>;
1.5 bowersj2 376:
377: # Now load in the contents
378: for my $value (split (/&/, $contents)) {
379: my ($name, $value) = split(/=/, $value);
380: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
381: $self->{VARS}->{$name} = $value;
382: }
383:
1.3 bowersj2 384: $file->close();
385: } else {
386: # Only valid if we're just starting.
387: if ($self->{STATE} ne 'START') {
388: return undef;
389: }
390: # Must create the storage
391: $self->{TOKEN} = md5_hex($ENV{'user.name'} . $ENV{'user.domain'} .
392: time() . rand());
393: $self->{FILENAME} = $Apache::lonnet::tmpdir . md5_hex($self->{TOKEN});
394: }
395:
396: # OK, we now have our persistent storage.
397:
398: if (defined $ENV{"form.RETURN_PAGE"})
399: {
400: $self->{RETURN_PAGE} = $ENV{"form.RETURN_PAGE"};
401: }
402: else
403: {
404: $self->{RETURN_PAGE} = $ENV{REFERER};
405: }
406:
407: $self->{STATES} = {};
408: $self->{DONE} = 0;
409:
1.9 bowersj2 410: # Used by various helpers for various things; see lonparm.helper
411: # for an example.
412: $self->{DATA} = {};
413:
1.13 bowersj2 414: $helper = $self;
415:
416: # Establish the $paramHash
417: $paramHash = {};
418:
1.3 bowersj2 419: bless($self, $class);
420: return $self;
421: }
422:
423: # Private function; returns a string to construct the hidden fields
424: # necessary to have the helper track state.
425: sub _saveVars {
426: my $self = shift;
427: my $result = "";
428: $result .= '<input type="hidden" name="CURRENT_STATE" value="' .
429: HTML::Entities::encode($self->{STATE}) . "\" />\n";
430: $result .= '<input type="hidden" name="TOKEN" value="' .
431: $self->{TOKEN} . "\" />\n";
432: $result .= '<input type="hidden" name="RETURN_PAGE" value="' .
433: HTML::Entities::encode($self->{RETURN_PAGE}) . "\" />\n";
434:
435: return $result;
436: }
437:
438: # Private function: Create the querystring-like representation of the stored
439: # data to write to disk.
440: sub _varsInFile {
441: my $self = shift;
442: my @vars = ();
443: for my $key (keys %{$self->{VARS}}) {
444: push @vars, &Apache::lonnet::escape($key) . '=' .
445: &Apache::lonnet::escape($self->{VARS}->{$key});
446: }
447: return join ('&', @vars);
448: }
449:
1.5 bowersj2 450: # Use this to declare variables.
451: # FIXME: Document this
452: sub declareVar {
453: my $self = shift;
454: my $var = shift;
455:
456: if (!defined($self->{VARS}->{$var})) {
457: $self->{VARS}->{$var} = '';
458: }
459:
460: my $envname = 'form.' . $var . '.forminput';
461: if (defined($ENV{$envname})) {
1.28 ! bowersj2 462: if (ref($ENV{$envname})) {
! 463: $self->{VARS}->{$var} = join('|||', @{$ENV{$envname}});
! 464: } else {
! 465: $self->{VARS}->{$var} = $ENV{$envname};
! 466: }
1.5 bowersj2 467: }
468: }
469:
1.3 bowersj2 470: sub changeState {
471: my $self = shift;
472: $self->{STATE} = shift;
473: }
474:
475: sub registerState {
476: my $self = shift;
477: my $state = shift;
478:
479: my $stateName = $state->name();
480: $self->{STATES}{$stateName} = $state;
481: }
482:
1.13 bowersj2 483: sub process {
1.3 bowersj2 484: my $self = shift;
485:
486: # Phase 1: Post processing for state of previous screen (which is actually
487: # the "current state" in terms of the helper variables), if it wasn't the
488: # beginning state.
489: if ($self->{STATE} ne "START" || $ENV{"form.SUBMIT"} eq "Next ->") {
490: my $prevState = $self->{STATES}{$self->{STATE}};
1.13 bowersj2 491: $prevState->postprocess();
1.3 bowersj2 492: }
493:
494: # Note, to handle errors in a state's input that a user must correct,
495: # do not transition in the postprocess, and force the user to correct
496: # the error.
497:
498: # Phase 2: Preprocess current state
499: my $startState = $self->{STATE};
1.17 bowersj2 500: my $state = $self->{STATES}->{$startState};
1.3 bowersj2 501:
1.13 bowersj2 502: # For debugging, print something here to determine if you're going
503: # to an undefined state.
1.3 bowersj2 504: if (!defined($state)) {
1.13 bowersj2 505: return;
1.3 bowersj2 506: }
507: $state->preprocess();
508:
509: # Phase 3: While the current state is different from the previous state,
510: # keep processing.
1.17 bowersj2 511: while ( $startState ne $self->{STATE} &&
512: defined($self->{STATES}->{$self->{STATE}}) )
1.3 bowersj2 513: {
514: $startState = $self->{STATE};
1.17 bowersj2 515: $state = $self->{STATES}->{$startState};
1.3 bowersj2 516: $state->preprocess();
517: }
518:
1.13 bowersj2 519: return;
520: }
521:
522: # 1: Do the post processing for the previous state.
523: # 2: Do the preprocessing for the current state.
524: # 3: Check to see if state changed, if so, postprocess current and move to next.
525: # Repeat until state stays stable.
526: # 4: Render the current state to the screen as an HTML page.
527: sub display {
528: my $self = shift;
529:
530: my $state = $self->{STATES}{$self->{STATE}};
531:
532: my $result = "";
533:
1.17 bowersj2 534: if (!defined($state)) {
535: $result = "<font color='#ff0000'>Error: state '$state' not defined!</font>";
536: return $result;
537: }
538:
1.3 bowersj2 539: # Phase 4: Display.
540: my $stateTitle = $state->title();
541: my $bodytag = &Apache::loncommon::bodytag("$self->{TITLE}",'','');
542:
543: $result .= <<HEADER;
544: <html>
545: <head>
546: <title>LON-CAPA Helper: $self->{TITLE}</title>
547: </head>
548: $bodytag
549: HEADER
1.28 ! bowersj2 550: if (!$state->overrideForm()) { $result.="<form name='helpform' method='POST'>"; }
1.3 bowersj2 551: $result .= <<HEADER;
552: <table border="0"><tr><td>
553: <h2><i>$stateTitle</i></h2>
554: HEADER
555:
556: if (!$state->overrideForm()) {
557: $result .= $self->_saveVars();
558: }
559: $result .= $state->render() . "<p> </p>";
560:
561: if (!$state->overrideForm()) {
562: $result .= '<center>';
563: if ($self->{STATE} ne $self->{START_STATE}) {
564: #$result .= '<input name="SUBMIT" type="submit" value="<- Previous" /> ';
565: }
566: if ($self->{DONE}) {
567: my $returnPage = $self->{RETURN_PAGE};
568: $result .= "<a href=\"$returnPage\">End Helper</a>";
569: }
570: else {
571: $result .= '<input name="back" type="button" ';
572: $result .= 'value="<- Previous" onclick="history.go(-1)" /> ';
573: $result .= '<input name="SUBMIT" type="submit" value="Next ->" />';
574: }
575: $result .= "</center>\n";
576: }
577:
1.13 bowersj2 578: #foreach my $key (keys %{$self->{VARS}}) {
579: # $result .= "|$key| -> " . $self->{VARS}->{$key} . "<br />";
580: #}
1.5 bowersj2 581:
1.3 bowersj2 582: $result .= <<FOOTER;
583: </td>
584: </tr>
585: </table>
586: </form>
587: </body>
588: </html>
589: FOOTER
590:
591: # Handle writing out the vars to the file
592: my $file = Apache::File->new('>'.$self->{FILENAME});
593: print $file $self->_varsInFile();
594:
595: return $result;
596: }
597:
598: 1;
599:
600: package Apache::lonhelper::state;
601:
602: # States bundle things together and are responsible for compositing the
1.4 bowersj2 603: # various elements together. It is not generally necessary for users to
604: # use the state object directly, so it is not perldoc'ed.
605:
606: # Basically, all the states do is pass calls to the elements and aggregate
607: # the results.
1.3 bowersj2 608:
609: sub new {
610: my $proto = shift;
611: my $class = ref($proto) || $proto;
612: my $self = {};
613:
614: $self->{NAME} = shift;
615: $self->{TITLE} = shift;
616: $self->{ELEMENTS} = [];
617:
618: bless($self, $class);
619:
620: $helper->registerState($self);
621:
1.13 bowersj2 622: $state = $self;
623:
1.3 bowersj2 624: return $self;
625: }
626:
627: sub name {
628: my $self = shift;
629: return $self->{NAME};
630: }
631:
632: sub title {
633: my $self = shift;
634: return $self->{TITLE};
635: }
636:
1.4 bowersj2 637: sub preprocess {
638: my $self = shift;
639: for my $element (@{$self->{ELEMENTS}}) {
640: $element->preprocess();
641: }
642: }
643:
1.6 bowersj2 644: # FIXME: Document that all postprocesses must return a true value or
645: # the state transition will be overridden
1.4 bowersj2 646: sub postprocess {
647: my $self = shift;
1.6 bowersj2 648:
649: # Save the state so we can roll it back if we need to.
650: my $originalState = $helper->{STATE};
651: my $everythingSuccessful = 1;
652:
1.4 bowersj2 653: for my $element (@{$self->{ELEMENTS}}) {
1.6 bowersj2 654: my $result = $element->postprocess();
655: if (!$result) { $everythingSuccessful = 0; }
656: }
657:
658: # If not all the postprocesses were successful, override
659: # any state transitions that may have occurred. It is the
660: # responsibility of the states to make sure they have
661: # error handling in that case.
662: if (!$everythingSuccessful) {
663: $helper->{STATE} = $originalState;
1.4 bowersj2 664: }
665: }
666:
1.13 bowersj2 667: # Override the form if any element wants to.
668: # two elements overriding the form will make a mess, but that should
669: # be considered helper author error ;-)
1.4 bowersj2 670: sub overrideForm {
1.13 bowersj2 671: my $self = shift;
672: for my $element (@{$self->{ELEMENTS}}) {
673: if ($element->overrideForm()) {
674: return 1;
675: }
676: }
1.4 bowersj2 677: return 0;
678: }
679:
680: sub addElement {
681: my $self = shift;
682: my $element = shift;
683:
684: push @{$self->{ELEMENTS}}, $element;
685: }
686:
1.28 ! bowersj2 687: use Data::Dumper;
1.4 bowersj2 688: sub render {
689: my $self = shift;
690: my @results = ();
691:
692: for my $element (@{$self->{ELEMENTS}}) {
693: push @results, $element->render();
694: }
1.28 ! bowersj2 695:
1.4 bowersj2 696: return join("\n", @results);
697: }
698:
699: 1;
700:
701: package Apache::lonhelper::element;
702: # Support code for elements
703:
704: =pod
705:
706: =head2 Element Base Class
707:
1.28 ! bowersj2 708: The Apache::lonhelper::element base class provides support for elements
! 709: and defines some generally useful tags for use in elements.
1.4 bowersj2 710:
1.25 bowersj2 711: B<finalcode tag>
712:
713: Each element can contain a "finalcode" tag that, when the special FINAL
714: helper state is used, will be executed, surrounded by "sub { my $helper = shift;"
715: and "}". It is expected to return a string describing what it did, which
716: may be an empty string. See course initialization helper for an example. This is
717: generally intended for helpers like the course initialization helper, which consist
718: of several panels, each of which is performing some sort of bite-sized functionality.
719:
720: B<defaultvalue tag>
721:
722: Each element that accepts user input can contain a "defaultvalue" tag that,
723: when surrounded by "sub { my $helper = shift; my $state = shift; " and "}",
724: will form a subroutine that when called will provide a default value for
725: the element. How this value is interpreted by the element is specific to
726: the element itself, and possibly the settings the element has (such as
727: multichoice vs. single choice for <choices> tags).
728:
729: This is also intended for things like the course initialization wizard, where the
730: user is setting various parameters. By correctly grabbing current settings
731: and including them into the helper, it allows the user to come back to the
732: helper later and re-execute it, without needing to worry about overwriting
733: some setting accidentally.
734:
735: Again, see the course initialization helper for examples.
736:
1.4 bowersj2 737: =cut
738:
1.5 bowersj2 739: BEGIN {
1.7 bowersj2 740: &Apache::lonhelper::register('Apache::lonhelper::element',
1.25 bowersj2 741: ('nextstate', 'finalcode',
742: 'defaultvalue'));
1.5 bowersj2 743: }
744:
1.4 bowersj2 745: # Because we use the param hash, this is often a sufficent
746: # constructor
747: sub new {
748: my $proto = shift;
749: my $class = ref($proto) || $proto;
750: my $self = $paramHash;
751: bless($self, $class);
752:
753: $self->{PARAMS} = $paramHash;
754: $self->{STATE} = $state;
755: $state->addElement($self);
756:
757: # Ensure param hash is not reused
758: $paramHash = {};
759:
760: return $self;
761: }
762:
1.5 bowersj2 763: sub start_nextstate {
764: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
765:
766: if ($target ne 'helper') {
767: return '';
768: }
769:
770: $paramHash->{NEXTSTATE} = &Apache::lonxml::get_all_text('/nextstate',
771: $parser);
772: return '';
773: }
774:
775: sub end_nextstate { return ''; }
776:
1.25 bowersj2 777: sub start_finalcode {
778: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
779:
780: if ($target ne 'helper') {
781: return '';
782: }
783:
784: $paramHash->{FINAL_CODE} = &Apache::lonxml::get_all_text('/finalcode',
785: $parser);
786: return '';
787: }
788:
789: sub end_finalcode { return ''; }
790:
791: sub start_defaultvalue {
792: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
793:
794: if ($target ne 'helper') {
795: return '';
796: }
797:
798: $paramHash->{DEFAULT_VALUE} = &Apache::lonxml::get_all_text('/defaultvalue',
799: $parser);
800: $paramHash->{DEFAULT_VALUE} = 'sub { my $helper = shift; my $state = shift;' .
801: $paramHash->{DEFAULT_VALUE} . '}';
802: return '';
803: }
804:
805: sub end_defaultvalue { return ''; }
806:
1.4 bowersj2 807: sub preprocess {
808: return 1;
809: }
810:
811: sub postprocess {
812: return 1;
813: }
814:
815: sub render {
816: return '';
817: }
818:
1.13 bowersj2 819: sub overrideForm {
820: return 0;
821: }
822:
1.4 bowersj2 823: 1;
824:
825: package Apache::lonhelper::message;
826:
827: =pod
828:
829: =head2 Element: message
830:
831: Message elements display the contents of their <message_text> tags, and
1.5 bowersj2 832: transition directly to the state in the <nextstate> tag. Example:
1.4 bowersj2 833:
834: <message>
1.5 bowersj2 835: <nextstate>GET_NAME</nextstate>
1.4 bowersj2 836: <message_text>This is the <b>message</b> the user will see,
837: <i>HTML allowed</i>.</message_text>
838: </message>
839:
1.5 bowersj2 840: This will display the HTML message and transition to the <nextstate> if
1.7 bowersj2 841: given. The HTML will be directly inserted into the helper, so if you don't
1.4 bowersj2 842: want text to run together, you'll need to manually wrap the <message_text>
843: in <p> tags, or whatever is appropriate for your HTML.
844:
1.5 bowersj2 845: Message tags do not add in whitespace, so if you want it, you'll need to add
846: it into states. This is done so you can inline some elements, such as
847: the <date> element, right between two messages, giving the appearence that
848: the <date> element appears inline. (Note the elements can not be embedded
849: within each other.)
850:
1.4 bowersj2 851: This is also a good template for creating your own new states, as it has
852: very little code beyond the state template.
853:
854: =cut
855:
856: no strict;
857: @ISA = ("Apache::lonhelper::element");
858: use strict;
859:
860: BEGIN {
1.7 bowersj2 861: &Apache::lonhelper::register('Apache::lonhelper::message',
1.10 bowersj2 862: ('message'));
1.3 bowersj2 863: }
864:
1.5 bowersj2 865: sub new {
866: my $ref = Apache::lonhelper::element->new();
867: bless($ref);
868: }
1.4 bowersj2 869:
870: # CONSTRUCTION: Construct the message element from the XML
871: sub start_message {
872: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
873:
874: if ($target ne 'helper') {
875: return '';
876: }
1.10 bowersj2 877:
878: $paramHash->{MESSAGE_TEXT} = &Apache::lonxml::get_all_text('/message',
879: $parser);
880:
881: if (defined($token->[2]{'nextstate'})) {
882: $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
883: }
1.4 bowersj2 884: return '';
1.3 bowersj2 885: }
886:
1.10 bowersj2 887: sub end_message {
1.4 bowersj2 888: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
889:
890: if ($target ne 'helper') {
891: return '';
892: }
1.10 bowersj2 893: Apache::lonhelper::message->new();
894: return '';
1.5 bowersj2 895: }
896:
897: sub render {
898: my $self = shift;
899:
900: return $self->{MESSAGE_TEXT};
901: }
902: # If a NEXTSTATE was given, switch to it
903: sub postprocess {
904: my $self = shift;
905: if (defined($self->{NEXTSTATE})) {
906: $helper->changeState($self->{NEXTSTATE});
907: }
1.6 bowersj2 908:
909: return 1;
1.5 bowersj2 910: }
911: 1;
912:
913: package Apache::lonhelper::choices;
914:
915: =pod
916:
917: =head2 Element: choices
918:
919: Choice states provide a single choice to the user as a text selection box.
920: A "choice" is two pieces of text, one which will be displayed to the user
921: (the "human" value), and one which will be passed back to the program
922: (the "computer" value). For instance, a human may choose from a list of
923: resources on disk by title, while your program wants the file name.
924:
925: <choices> takes an attribute "variable" to control which helper variable
926: the result is stored in.
927:
928: <choices> takes an attribute "multichoice" which, if set to a true
929: value, will allow the user to select multiple choices.
930:
1.26 bowersj2 931: <choices> takes an attribute "allowempty" which, if set to a true
932: value, will allow the user to select none of the choices without raising
933: an error message.
934:
1.5 bowersj2 935: B<SUB-TAGS>
936:
937: <choices> can have the following subtags:
938:
939: =over 4
940:
941: =item * <nextstate>state_name</nextstate>: If given, this will cause the
942: choice element to transition to the given state after executing. If
943: this is used, do not pass nextstates to the <choice> tag.
944:
945: =item * <choice />: If the choices are static,
946: this element will allow you to specify them. Each choice
947: contains attribute, "computer", as described above. The
948: content of the tag will be used as the human label.
949: For example,
950: <choice computer='234-12-7312'>Bobby McDormik</choice>.
951:
1.13 bowersj2 952: <choice> can take a parameter "eval", which if set to
953: a true value, will cause the contents of the tag to be
954: evaluated as it would be in an <eval> tag; see <eval> tag
955: below.
956:
1.5 bowersj2 957: <choice> may optionally contain a 'nextstate' attribute, which
958: will be the state transisitoned to if the choice is made, if
959: the choice is not multichoice.
960:
961: =back
962:
963: To create the choices programmatically, either wrap the choices in
964: <condition> tags (prefered), or use an <exec> block inside the <choice>
965: tag. Store the choices in $state->{CHOICES}, which is a list of list
966: references, where each list has three strings. The first is the human
967: name, the second is the computer name. and the third is the option
968: next state. For example:
969:
970: <exec>
971: for (my $i = 65; $i < 65 + 26; $i++) {
972: push @{$state->{CHOICES}}, [chr($i), $i, 'next'];
973: }
974: </exec>
975:
976: This will allow the user to select from the letters A-Z (in ASCII), while
977: passing the ASCII value back into the helper variables, and the state
978: will in all cases transition to 'next'.
979:
980: You can mix and match methods of creating choices, as long as you always
981: "push" onto the choice list, rather then wiping it out. (You can even
982: remove choices programmatically, but that would probably be bad form.)
983:
1.25 bowersj2 984: B<defaultvalue support>
985:
986: Choices supports default values both in multichoice and single choice mode.
987: In single choice mode, have the defaultvalue tag's function return the
988: computer value of the box you want checked. If the function returns a value
989: that does not correspond to any of the choices, the default behavior of selecting
990: the first choice will be preserved.
991:
992: For multichoice, return a string with the computer values you want checked,
993: delimited by triple pipes. Note this matches how the result of the <choices>
994: tag is stored in the {VARS} hash.
995:
1.5 bowersj2 996: =cut
997:
998: no strict;
999: @ISA = ("Apache::lonhelper::element");
1000: use strict;
1001:
1002: BEGIN {
1.7 bowersj2 1003: &Apache::lonhelper::register('Apache::lonhelper::choices',
1.5 bowersj2 1004: ('choice', 'choices'));
1005: }
1006:
1007: sub new {
1008: my $ref = Apache::lonhelper::element->new();
1009: bless($ref);
1010: }
1011:
1012: # CONSTRUCTION: Construct the message element from the XML
1013: sub start_choices {
1014: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1015:
1016: if ($target ne 'helper') {
1017: return '';
1018: }
1019:
1020: # Need to initialize the choices list, so everything can assume it exists
1.24 sakharuk 1021: $paramHash->{'variable'} = $token->[2]{'variable'} if (!defined($paramHash->{'variable'}));
1.5 bowersj2 1022: $helper->declareVar($paramHash->{'variable'});
1023: $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.26 bowersj2 1024: $paramHash->{'allowempty'} = $token->[2]{'allowempty'};
1.5 bowersj2 1025: $paramHash->{CHOICES} = [];
1026: return '';
1027: }
1028:
1029: sub end_choices {
1030: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1031:
1032: if ($target ne 'helper') {
1033: return '';
1034: }
1035: Apache::lonhelper::choices->new();
1036: return '';
1037: }
1038:
1039: sub start_choice {
1040: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1041:
1042: if ($target ne 'helper') {
1043: return '';
1044: }
1045:
1046: my $computer = $token->[2]{'computer'};
1047: my $human = &Apache::lonxml::get_all_text('/choice',
1048: $parser);
1049: my $nextstate = $token->[2]{'nextstate'};
1.13 bowersj2 1050: my $evalFlag = $token->[2]{'eval'};
1051: push @{$paramHash->{CHOICES}}, [$human, $computer, $nextstate,
1052: $evalFlag];
1.5 bowersj2 1053: return '';
1054: }
1055:
1056: sub end_choice {
1057: return '';
1058: }
1059:
1060: sub render {
1061: # START HERE: Replace this with correct choices code.
1062: my $self = shift;
1063: my $var = $self->{'variable'};
1064: my $buttons = '';
1065: my $result = '';
1066:
1067: if ($self->{'multichoice'}) {
1.6 bowersj2 1068: $result .= <<SCRIPT;
1.5 bowersj2 1069: <script>
1.18 bowersj2 1070: function checkall(value, checkName) {
1.15 bowersj2 1071: for (i=0; i<document.forms.helpform.elements.length; i++) {
1.18 bowersj2 1072: ele = document.forms.helpform.elements[i];
1073: if (ele.name == checkName + '.forminput') {
1074: document.forms.helpform.elements[i].checked=value;
1075: }
1.5 bowersj2 1076: }
1077: }
1078: </script>
1079: SCRIPT
1.25 bowersj2 1080: }
1081:
1082: # Only print "select all" and "unselect all" if there are five or
1083: # more choices; fewer then that and it looks silly.
1084: if ($self->{'multichoice'} && scalar(@{$self->{CHOICES}}) > 4) {
1.5 bowersj2 1085: $buttons = <<BUTTONS;
1086: <br />
1.18 bowersj2 1087: <input type="button" onclick="checkall(true, '$var')" value="Select All" />
1088: <input type="button" onclick="checkall(false, '$var')" value="Unselect All" />
1.6 bowersj2 1089: <br />
1.5 bowersj2 1090: BUTTONS
1091: }
1092:
1.16 bowersj2 1093: if (defined $self->{ERROR_MSG}) {
1.6 bowersj2 1094: $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br />';
1.5 bowersj2 1095: }
1096:
1097: $result .= $buttons;
1.6 bowersj2 1098:
1.5 bowersj2 1099: $result .= "<table>\n\n";
1100:
1.25 bowersj2 1101: my %checkedChoices;
1102: my $checkedChoicesFunc;
1103:
1104: if (defined($self->{DEFAULT_VALUE})) {
1105: $checkedChoicesFunc = eval ($self->{DEFAULT_VALUE});
1106: die 'Error in default value code for variable ' .
1107: {'variable'} . ', Perl said:' . $@ if $@;
1108: } else {
1109: $checkedChoicesFunc = sub { return ''; };
1110: }
1111:
1112: # Process which choices should be checked.
1113: if ($self->{'multichoice'}) {
1114: for my $selectedChoice (split(/\|\|\|/, (&$checkedChoicesFunc($helper, $self)))) {
1115: $checkedChoices{$selectedChoice} = 1;
1116: }
1117: } else {
1118: # single choice
1119: my $selectedChoice = &$checkedChoicesFunc($helper, $self);
1120:
1121: my $foundChoice = 0;
1122:
1123: # check that the choice is in the list of choices.
1124: for my $choice (@{$self->{CHOICES}}) {
1125: if ($choice->[1] eq $selectedChoice) {
1126: $checkedChoices{$choice->[1]} = 1;
1127: $foundChoice = 1;
1128: }
1129: }
1130:
1131: # If we couldn't find the choice, pick the first one
1132: if (!$foundChoice) {
1133: $checkedChoices{$self->{CHOICES}->[0]->[1]} = 1;
1134: }
1135: }
1136:
1.5 bowersj2 1137: my $type = "radio";
1138: if ($self->{'multichoice'}) { $type = 'checkbox'; }
1139: foreach my $choice (@{$self->{CHOICES}}) {
1140: $result .= "<tr>\n<td width='20'> </td>\n";
1141: $result .= "<td valign='top'><input type='$type' name='$var.forminput'"
1142: . "' value='" .
1143: HTML::Entities::encode($choice->[1])
1144: . "'";
1.25 bowersj2 1145: if ($checkedChoices{$choice->[1]}) {
1.5 bowersj2 1146: $result .= " checked ";
1147: }
1.13 bowersj2 1148: my $choiceLabel = $choice->[0];
1149: if ($choice->[4]) { # if we need to evaluate this choice
1150: $choiceLabel = "sub { my $helper = shift; my $state = shift;" .
1151: $choiceLabel . "}";
1152: $choiceLabel = eval($choiceLabel);
1153: $choiceLabel = &$choiceLabel($helper, $self);
1154: }
1155: $result .= "/></td><td> " . $choiceLabel . "</td></tr>\n";
1.5 bowersj2 1156: }
1157: $result .= "</table>\n\n\n";
1158: $result .= $buttons;
1159:
1160: return $result;
1161: }
1162:
1163: # If a NEXTSTATE was given or a nextstate for this choice was
1164: # given, switch to it
1165: sub postprocess {
1166: my $self = shift;
1167: my $chosenValue = $ENV{'form.' . $self->{'variable'} . '.forminput'};
1168:
1.26 bowersj2 1169: if (!defined($chosenValue) && !$self->{'allowempty'}) {
1.6 bowersj2 1170: $self->{ERROR_MSG} = "You must choose one or more choices to" .
1171: " continue.";
1172: return 0;
1173: }
1174:
1.28 ! bowersj2 1175: if (ref($chosenValue)) {
! 1176: $helper->{VARS}->{$self->{'variable'}} = join('|||', @$chosenValue);
1.6 bowersj2 1177: }
1178:
1.5 bowersj2 1179: if (defined($self->{NEXTSTATE})) {
1180: $helper->changeState($self->{NEXTSTATE});
1181: }
1182:
1183: foreach my $choice (@{$self->{CHOICES}}) {
1184: if ($choice->[1] eq $chosenValue) {
1185: if (defined($choice->[2])) {
1186: $helper->changeState($choice->[2]);
1187: }
1188: }
1189: }
1.6 bowersj2 1190: return 1;
1.5 bowersj2 1191: }
1192: 1;
1193:
1194: package Apache::lonhelper::date;
1195:
1196: =pod
1197:
1198: =head2 Element: date
1199:
1200: Date elements allow the selection of a date with a drop down list.
1201:
1202: Date elements can take two attributes:
1203:
1204: =over 4
1205:
1206: =item * B<variable>: The name of the variable to store the chosen
1207: date in. Required.
1208:
1209: =item * B<hoursminutes>: If a true value, the date will show hours
1210: and minutes, as well as month/day/year. If false or missing,
1211: the date will only show the month, day, and year.
1212:
1213: =back
1214:
1215: Date elements contain only an option <nextstate> tag to determine
1216: the next state.
1217:
1218: Example:
1219:
1220: <date variable="DUE_DATE" hoursminutes="1">
1221: <nextstate>choose_why</nextstate>
1222: </date>
1223:
1224: =cut
1225:
1226: no strict;
1227: @ISA = ("Apache::lonhelper::element");
1228: use strict;
1229:
1230: use Time::localtime;
1231:
1232: BEGIN {
1.7 bowersj2 1233: &Apache::lonhelper::register('Apache::lonhelper::date',
1.5 bowersj2 1234: ('date'));
1235: }
1236:
1237: # Don't need to override the "new" from element
1238: sub new {
1239: my $ref = Apache::lonhelper::element->new();
1240: bless($ref);
1241: }
1242:
1243: my @months = ("January", "February", "March", "April", "May", "June", "July",
1244: "August", "September", "October", "November", "December");
1245:
1246: # CONSTRUCTION: Construct the message element from the XML
1247: sub start_date {
1248: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1249:
1250: if ($target ne 'helper') {
1251: return '';
1252: }
1253:
1254: $paramHash->{'variable'} = $token->[2]{'variable'};
1255: $helper->declareVar($paramHash->{'variable'});
1256: $paramHash->{'hoursminutes'} = $token->[2]{'hoursminutes'};
1257: }
1258:
1259: sub end_date {
1260: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1261:
1262: if ($target ne 'helper') {
1263: return '';
1264: }
1265: Apache::lonhelper::date->new();
1266: return '';
1267: }
1268:
1269: sub render {
1270: my $self = shift;
1271: my $result = "";
1272: my $var = $self->{'variable'};
1273:
1274: my $date;
1275:
1276: # Default date: The current hour.
1277: $date = localtime();
1278: $date->min(0);
1279:
1280: if (defined $self->{ERROR_MSG}) {
1281: $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
1282: }
1283:
1284: # Month
1285: my $i;
1286: $result .= "<select name='${var}month'>\n";
1287: for ($i = 0; $i < 12; $i++) {
1288: if ($i == $date->mon) {
1289: $result .= "<option value='$i' selected>";
1290: } else {
1291: $result .= "<option value='$i'>";
1292: }
1293: $result .= $months[$i] . "</option>\n";
1294: }
1295: $result .= "</select>\n";
1296:
1297: # Day
1298: $result .= "<select name='${var}day'>\n";
1299: for ($i = 1; $i < 32; $i++) {
1300: if ($i == $date->mday) {
1301: $result .= '<option selected>';
1302: } else {
1303: $result .= '<option>';
1304: }
1305: $result .= "$i</option>\n";
1306: }
1307: $result .= "</select>,\n";
1308:
1309: # Year
1310: $result .= "<select name='${var}year'>\n";
1311: for ($i = 2000; $i < 2030; $i++) { # update this after 64-bit dates
1312: if ($date->year + 1900 == $i) {
1313: $result .= "<option selected>";
1314: } else {
1315: $result .= "<option>";
1316: }
1317: $result .= "$i</option>\n";
1318: }
1319: $result .= "</select>,\n";
1320:
1321: # Display Hours and Minutes if they are called for
1322: if ($self->{'hoursminutes'}) {
1323: # Build hour
1324: $result .= "<select name='${var}hour'>\n";
1325: $result .= "<option " . ($date->hour == 0 ? 'selected ':'') .
1326: " value='0'>midnight</option>\n";
1327: for ($i = 1; $i < 12; $i++) {
1328: if ($date->hour == $i) {
1329: $result .= "<option selected value='$i'>$i a.m.</option>\n";
1330: } else {
1331: $result .= "<option value='$i'>$i a.m</option>\n";
1332: }
1333: }
1334: $result .= "<option " . ($date->hour == 12 ? 'selected ':'') .
1335: " value='12'>noon</option>\n";
1336: for ($i = 13; $i < 24; $i++) {
1337: my $printedHour = $i - 12;
1338: if ($date->hour == $i) {
1339: $result .= "<option selected value='$i'>$printedHour p.m.</option>\n";
1340: } else {
1341: $result .= "<option value='$i'>$printedHour p.m.</option>\n";
1342: }
1343: }
1344:
1345: $result .= "</select> :\n";
1346:
1347: $result .= "<select name='${var}minute'>\n";
1348: for ($i = 0; $i < 60; $i++) {
1349: my $printedMinute = $i;
1350: if ($i < 10) {
1351: $printedMinute = "0" . $printedMinute;
1352: }
1353: if ($date->min == $i) {
1354: $result .= "<option selected>";
1355: } else {
1356: $result .= "<option>";
1357: }
1358: $result .= "$printedMinute</option>\n";
1359: }
1360: $result .= "</select>\n";
1361: }
1362:
1363: return $result;
1364:
1365: }
1366: # If a NEXTSTATE was given, switch to it
1367: sub postprocess {
1368: my $self = shift;
1369: my $var = $self->{'variable'};
1370: my $month = $ENV{'form.' . $var . 'month'};
1371: my $day = $ENV{'form.' . $var . 'day'};
1372: my $year = $ENV{'form.' . $var . 'year'};
1373: my $min = 0;
1374: my $hour = 0;
1375: if ($self->{'hoursminutes'}) {
1376: $min = $ENV{'form.' . $var . 'minute'};
1377: $hour = $ENV{'form.' . $var . 'hour'};
1378: }
1379:
1380: my $chosenDate = Time::Local::timelocal(0, $min, $hour, $day, $month, $year);
1381: # Check to make sure that the date was not automatically co-erced into a
1382: # valid date, as we want to flag that as an error
1383: # This happens for "Feb. 31", for instance, which is coerced to March 2 or
1384: # 3, depending on if it's a leapyear
1385: my $checkDate = localtime($chosenDate);
1386:
1387: if ($checkDate->mon != $month || $checkDate->mday != $day ||
1388: $checkDate->year + 1900 != $year) {
1389: $self->{ERROR_MSG} = "Can't use " . $months[$month] . " $day, $year as a "
1390: . "date because it doesn't exist. Please enter a valid date.";
1.6 bowersj2 1391: return 0;
1.5 bowersj2 1392: }
1393:
1394: $helper->{VARS}->{$var} = $chosenDate;
1395:
1396: if (defined($self->{NEXTSTATE})) {
1397: $helper->changeState($self->{NEXTSTATE});
1398: }
1.6 bowersj2 1399:
1400: return 1;
1.5 bowersj2 1401: }
1402: 1;
1403:
1404: package Apache::lonhelper::resource;
1405:
1406: =pod
1407:
1408: =head2 Element: resource
1409:
1410: <resource> elements allow the user to select one or multiple resources
1411: from the current course. You can filter out which resources they can view,
1412: and filter out which resources they can select. The course will always
1413: be displayed fully expanded, because of the difficulty of maintaining
1414: selections across folder openings and closings. If this is fixed, then
1415: the user can manipulate the folders.
1416:
1417: <resource> takes the standard variable attribute to control what helper
1418: variable stores the results. It also takes a "multichoice" attribute,
1.17 bowersj2 1419: which controls whether the user can select more then one resource. The
1420: "toponly" attribute controls whether the resource display shows just the
1421: resources in that sequence, or recurses into all sub-sequences, defaulting
1422: to false.
1.5 bowersj2 1423:
1424: B<SUB-TAGS>
1425:
1426: =over 4
1427:
1428: =item * <filterfunc>: If you want to filter what resources are displayed
1429: to the user, use a filter func. The <filterfunc> tag should contain
1430: Perl code that when wrapped with "sub { my $res = shift; " and "}" is
1431: a function that returns true if the resource should be displayed,
1432: and false if it should be skipped. $res is a resource object.
1433: (See Apache::lonnavmaps documentation for information about the
1434: resource object.)
1435:
1436: =item * <choicefunc>: Same as <filterfunc>, except that controls whether
1437: the given resource can be chosen. (It is almost always a good idea to
1438: show the user the folders, for instance, but you do not always want to
1439: let the user select them.)
1440:
1441: =item * <nextstate>: Standard nextstate behavior.
1442:
1443: =item * <valuefunc>: This function controls what is returned by the resource
1444: when the user selects it. Like filterfunc and choicefunc, it should be
1445: a function fragment that when wrapped by "sub { my $res = shift; " and
1446: "}" returns a string representing what you want to have as the value. By
1447: default, the value will be the resource ID of the object ($res->{ID}).
1448:
1.13 bowersj2 1449: =item * <mapurl>: If the URL of a map is given here, only that map
1450: will be displayed, instead of the whole course.
1451:
1.5 bowersj2 1452: =back
1453:
1454: =cut
1455:
1456: no strict;
1457: @ISA = ("Apache::lonhelper::element");
1458: use strict;
1459:
1460: BEGIN {
1.7 bowersj2 1461: &Apache::lonhelper::register('Apache::lonhelper::resource',
1.5 bowersj2 1462: ('resource', 'filterfunc',
1.13 bowersj2 1463: 'choicefunc', 'valuefunc',
1464: 'mapurl'));
1.5 bowersj2 1465: }
1466:
1467: sub new {
1468: my $ref = Apache::lonhelper::element->new();
1469: bless($ref);
1470: }
1471:
1472: # CONSTRUCTION: Construct the message element from the XML
1473: sub start_resource {
1474: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1475:
1476: if ($target ne 'helper') {
1477: return '';
1478: }
1479:
1480: $paramHash->{'variable'} = $token->[2]{'variable'};
1481: $helper->declareVar($paramHash->{'variable'});
1.14 bowersj2 1482: $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.17 bowersj2 1483: $paramHash->{'toponly'} = $token->[2]{'toponly'};
1.5 bowersj2 1484: return '';
1485: }
1486:
1487: sub end_resource {
1488: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1489:
1490: if ($target ne 'helper') {
1491: return '';
1492: }
1493: if (!defined($paramHash->{FILTER_FUNC})) {
1494: $paramHash->{FILTER_FUNC} = sub {return 1;};
1495: }
1496: if (!defined($paramHash->{CHOICE_FUNC})) {
1497: $paramHash->{CHOICE_FUNC} = sub {return 1;};
1498: }
1499: if (!defined($paramHash->{VALUE_FUNC})) {
1500: $paramHash->{VALUE_FUNC} = sub {my $res = shift; return $res->{ID}; };
1501: }
1502: Apache::lonhelper::resource->new();
1.4 bowersj2 1503: return '';
1504: }
1505:
1.5 bowersj2 1506: sub start_filterfunc {
1507: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1508:
1509: if ($target ne 'helper') {
1510: return '';
1511: }
1512:
1513: my $contents = Apache::lonxml::get_all_text('/filterfunc',
1514: $parser);
1515: $contents = 'sub { my $res = shift; ' . $contents . '}';
1516: $paramHash->{FILTER_FUNC} = eval $contents;
1517: }
1518:
1519: sub end_filterfunc { return ''; }
1520:
1521: sub start_choicefunc {
1522: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1523:
1524: if ($target ne 'helper') {
1525: return '';
1526: }
1527:
1528: my $contents = Apache::lonxml::get_all_text('/choicefunc',
1529: $parser);
1530: $contents = 'sub { my $res = shift; ' . $contents . '}';
1531: $paramHash->{CHOICE_FUNC} = eval $contents;
1532: }
1533:
1534: sub end_choicefunc { return ''; }
1535:
1536: sub start_valuefunc {
1537: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1538:
1539: if ($target ne 'helper') {
1540: return '';
1541: }
1542:
1543: my $contents = Apache::lonxml::get_all_text('/valuefunc',
1544: $parser);
1545: $contents = 'sub { my $res = shift; ' . $contents . '}';
1546: $paramHash->{VALUE_FUNC} = eval $contents;
1547: }
1548:
1549: sub end_valuefunc { return ''; }
1550:
1.13 bowersj2 1551: sub start_mapurl {
1552: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1553:
1554: if ($target ne 'helper') {
1555: return '';
1556: }
1557:
1558: my $contents = Apache::lonxml::get_all_text('/mapurl',
1559: $parser);
1.14 bowersj2 1560: $paramHash->{MAP_URL} = $contents;
1.13 bowersj2 1561: }
1562:
1563: sub end_mapurl { return ''; }
1564:
1.5 bowersj2 1565: # A note, in case I don't get to this before I leave.
1566: # If someone complains about the "Back" button returning them
1567: # to the previous folder state, instead of returning them to
1568: # the previous helper state, the *correct* answer is for the helper
1569: # to keep track of how many times the user has manipulated the folders,
1570: # and feed that to the history.go() call in the helper rendering routines.
1571: # If done correctly, the helper itself can keep track of how many times
1572: # it renders the same states, so it doesn't go in just this state, and
1573: # you can lean on the browser back button to make sure it all chains
1574: # correctly.
1575: # Right now, though, I'm just forcing all folders open.
1576:
1577: sub render {
1578: my $self = shift;
1579: my $result = "";
1580: my $var = $self->{'variable'};
1581: my $curVal = $helper->{VARS}->{$var};
1582:
1.15 bowersj2 1583: my $buttons = '';
1584:
1585: if ($self->{'multichoice'}) {
1586: $result = <<SCRIPT;
1587: <script>
1.18 bowersj2 1588: function checkall(value, checkName) {
1.15 bowersj2 1589: for (i=0; i<document.forms.helpform.elements.length; i++) {
1590: ele = document.forms.helpform.elements[i];
1.18 bowersj2 1591: if (ele.name == checkName + '.forminput') {
1.15 bowersj2 1592: document.forms.helpform.elements[i].checked=value;
1593: }
1594: }
1595: }
1596: </script>
1597: SCRIPT
1598: $buttons = <<BUTTONS;
1599: <br />
1.18 bowersj2 1600: <input type="button" onclick="checkall(true, '$var')" value="Select All Resources" />
1601: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Resources" />
1.15 bowersj2 1602: <br />
1603: BUTTONS
1604: }
1605:
1.5 bowersj2 1606: if (defined $self->{ERROR_MSG}) {
1.14 bowersj2 1607: $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
1.5 bowersj2 1608: }
1609:
1.15 bowersj2 1610: $result .= $buttons;
1611:
1.5 bowersj2 1612: my $filterFunc = $self->{FILTER_FUNC};
1613: my $choiceFunc = $self->{CHOICE_FUNC};
1614: my $valueFunc = $self->{VALUE_FUNC};
1.13 bowersj2 1615: my $mapUrl = $self->{MAP_URL};
1.14 bowersj2 1616: my $multichoice = $self->{'multichoice'};
1.5 bowersj2 1617:
1618: # Create the composite function that renders the column on the nav map
1619: # have to admit any language that lets me do this can't be all bad
1620: # - Jeremy (Pythonista) ;-)
1621: my $checked = 0;
1622: my $renderColFunc = sub {
1623: my ($resource, $part, $params) = @_;
1.14 bowersj2 1624:
1625: my $inputType;
1626: if ($multichoice) { $inputType = 'checkbox'; }
1627: else {$inputType = 'radio'; }
1628:
1.5 bowersj2 1629: if (!&$choiceFunc($resource)) {
1630: return '<td> </td>';
1631: } else {
1.14 bowersj2 1632: my $col = "<td><input type='$inputType' name='${var}.forminput' ";
1633: if (!$checked && !$multichoice) {
1.5 bowersj2 1634: $col .= "checked ";
1635: $checked = 1;
1636: }
1637: $col .= "value='" .
1638: HTML::Entities::encode(&$valueFunc($resource))
1639: . "' /></td>";
1640: return $col;
1641: }
1642: };
1643:
1.17 bowersj2 1644: $ENV{'form.condition'} = !$self->{'toponly'};
1.5 bowersj2 1645: $result .=
1646: &Apache::lonnavmaps::render( { 'cols' => [$renderColFunc,
1647: Apache::lonnavmaps::resource()],
1648: 'showParts' => 0,
1649: 'filterFunc' => $filterFunc,
1.13 bowersj2 1650: 'resource_no_folder_link' => 1,
1651: 'iterator_map' => $mapUrl }
1.5 bowersj2 1652: );
1.15 bowersj2 1653:
1654: $result .= $buttons;
1.5 bowersj2 1655:
1656: return $result;
1657: }
1658:
1659: sub postprocess {
1660: my $self = shift;
1.14 bowersj2 1661:
1662: if ($self->{'multichoice'} && !$helper->{VARS}->{$self->{'variable'}}) {
1663: $self->{ERROR_MSG} = 'You must choose at least one resource to continue.';
1664: return 0;
1665: }
1666:
1.5 bowersj2 1667: if (defined($self->{NEXTSTATE})) {
1668: $helper->changeState($self->{NEXTSTATE});
1669: }
1.6 bowersj2 1670:
1671: return 1;
1.5 bowersj2 1672: }
1673:
1674: 1;
1675:
1676: package Apache::lonhelper::student;
1677:
1678: =pod
1679:
1680: =head2 Element: student
1681:
1682: Student elements display a choice of students enrolled in the current
1683: course. Currently it is primitive; this is expected to evolve later.
1684:
1685: Student elements take two attributes: "variable", which means what
1686: it usually does, and "multichoice", which if true allows the user
1687: to select multiple students.
1688:
1689: =cut
1690:
1691: no strict;
1692: @ISA = ("Apache::lonhelper::element");
1693: use strict;
1694:
1695:
1696:
1697: BEGIN {
1.7 bowersj2 1698: &Apache::lonhelper::register('Apache::lonhelper::student',
1.5 bowersj2 1699: ('student'));
1700: }
1701:
1702: sub new {
1703: my $ref = Apache::lonhelper::element->new();
1704: bless($ref);
1705: }
1.4 bowersj2 1706:
1.5 bowersj2 1707: sub start_student {
1.4 bowersj2 1708: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1709:
1710: if ($target ne 'helper') {
1711: return '';
1712: }
1713:
1.5 bowersj2 1714: $paramHash->{'variable'} = $token->[2]{'variable'};
1715: $helper->declareVar($paramHash->{'variable'});
1716: $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.12 bowersj2 1717: if (defined($token->[2]{'nextstate'})) {
1718: $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
1719: }
1720:
1.5 bowersj2 1721: }
1722:
1723: sub end_student {
1724: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1725:
1726: if ($target ne 'helper') {
1727: return '';
1728: }
1729: Apache::lonhelper::student->new();
1.3 bowersj2 1730: }
1.5 bowersj2 1731:
1732: sub render {
1733: my $self = shift;
1734: my $result = '';
1735: my $buttons = '';
1.18 bowersj2 1736: my $var = $self->{'variable'};
1.5 bowersj2 1737:
1738: if ($self->{'multichoice'}) {
1739: $result = <<SCRIPT;
1740: <script>
1.18 bowersj2 1741: function checkall(value, checkName) {
1.15 bowersj2 1742: for (i=0; i<document.forms.helpform.elements.length; i++) {
1.18 bowersj2 1743: ele = document.forms.helpform.elements[i];
1744: if (ele.name == checkName + '.forminput') {
1745: document.forms.helpform.elements[i].checked=value;
1746: }
1.5 bowersj2 1747: }
1748: }
1749: </script>
1750: SCRIPT
1751: $buttons = <<BUTTONS;
1752: <br />
1.18 bowersj2 1753: <input type="button" onclick="checkall(true, '$var')" value="Select All Students" />
1754: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Students" />
1.5 bowersj2 1755: <br />
1756: BUTTONS
1757: }
1758:
1759: if (defined $self->{ERROR_MSG}) {
1760: $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
1761: }
1762:
1763: # Load up the students
1764: my $choices = &Apache::loncoursedata::get_classlist();
1765: my @keys = keys %{$choices};
1766:
1767: # Constants
1768: my $section = Apache::loncoursedata::CL_SECTION();
1769: my $fullname = Apache::loncoursedata::CL_FULLNAME();
1770:
1771: # Sort by: Section, name
1772: @keys = sort {
1773: if ($choices->{$a}->[$section] ne $choices->{$b}->[$section]) {
1774: return $choices->{$a}->[$section] cmp $choices->{$b}->[$section];
1775: }
1776: return $choices->{$a}->[$fullname] cmp $choices->{$b}->[$fullname];
1777: } @keys;
1778:
1779: my $type = 'radio';
1780: if ($self->{'multichoice'}) { $type = 'checkbox'; }
1781: $result .= "<table cellspacing='2' cellpadding='2' border='0'>\n";
1782: $result .= "<tr><td></td><td align='center'><b>Student Name</b></td>".
1783: "<td align='center'><b>Section</b></td></tr>";
1784:
1785: my $checked = 0;
1786: foreach (@keys) {
1787: $result .= "<tr><td><input type='$type' name='" .
1788: $self->{'variable'} . '.forminput' . "'";
1789:
1790: if (!$self->{'multichoice'} && !$checked) {
1791: $result .= " checked ";
1792: $checked = 1;
1793: }
1794: $result .=
1.19 bowersj2 1795: " value='" . HTML::Entities::encode($_ . ':' . $choices->{$_}->[$section])
1.5 bowersj2 1796: . "' /></td><td>"
1797: . HTML::Entities::encode($choices->{$_}->[$fullname])
1798: . "</td><td align='center'>"
1799: . HTML::Entities::encode($choices->{$_}->[$section])
1800: . "</td></tr>\n";
1801: }
1802:
1803: $result .= "</table>\n\n";
1804: $result .= $buttons;
1.4 bowersj2 1805:
1.5 bowersj2 1806: return $result;
1807: }
1808:
1.6 bowersj2 1809: sub postprocess {
1810: my $self = shift;
1811:
1812: my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
1813: if (!$result) {
1814: $self->{ERROR_MSG} = 'You must choose at least one student '.
1815: 'to continue.';
1816: return 0;
1817: }
1818:
1819: if (defined($self->{NEXTSTATE})) {
1820: $helper->changeState($self->{NEXTSTATE});
1821: }
1822:
1823: return 1;
1824: }
1825:
1.5 bowersj2 1826: 1;
1827:
1828: package Apache::lonhelper::files;
1829:
1830: =pod
1831:
1832: =head2 Element: files
1833:
1834: files allows the users to choose files from a given directory on the
1835: server. It is always multichoice and stores the result as a triple-pipe
1836: delimited entry in the helper variables.
1837:
1838: Since it is extremely unlikely that you can actually code a constant
1839: representing the directory you wish to allow the user to search, <files>
1840: takes a subroutine that returns the name of the directory you wish to
1841: have the user browse.
1842:
1843: files accepts the attribute "variable" to control where the files chosen
1844: are put. It accepts the attribute "multichoice" as the other attribute,
1845: defaulting to false, which if true will allow the user to select more
1846: then one choice.
1847:
1848: <files> accepts three subtags. One is the "nextstate" sub-tag that works
1849: as it does with the other tags. Another is a <filechoice> sub tag that
1850: is Perl code that, when surrounded by "sub {" and "}" will return a
1851: string representing what directory on the server to allow the user to
1852: choose files from. Finally, the <filefilter> subtag should contain Perl
1853: code that when surrounded by "sub { my $filename = shift; " and "}",
1854: returns a true value if the user can pick that file, or false otherwise.
1855: The filename passed to the function will be just the name of the file,
1856: with no path info.
1857:
1858: =cut
1859:
1860: no strict;
1861: @ISA = ("Apache::lonhelper::element");
1862: use strict;
1863:
1864: BEGIN {
1.7 bowersj2 1865: &Apache::lonhelper::register('Apache::lonhelper::files',
1866: ('files', 'filechoice', 'filefilter'));
1.5 bowersj2 1867: }
1868:
1869: sub new {
1870: my $ref = Apache::lonhelper::element->new();
1871: bless($ref);
1872: }
1873:
1874: sub start_files {
1875: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1876:
1877: if ($target ne 'helper') {
1878: return '';
1879: }
1880: $paramHash->{'variable'} = $token->[2]{'variable'};
1881: $helper->declareVar($paramHash->{'variable'});
1882: $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1883: }
1884:
1885: sub end_files {
1886: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1887:
1888: if ($target ne 'helper') {
1889: return '';
1890: }
1891: if (!defined($paramHash->{FILTER_FUNC})) {
1892: $paramHash->{FILTER_FUNC} = sub { return 1; };
1893: }
1894: Apache::lonhelper::files->new();
1895: }
1896:
1897: sub start_filechoice {
1898: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1899:
1900: if ($target ne 'helper') {
1901: return '';
1902: }
1903: $paramHash->{'filechoice'} = Apache::lonxml::get_all_text('/filechoice',
1904: $parser);
1905: }
1906:
1907: sub end_filechoice { return ''; }
1908:
1909: sub start_filefilter {
1910: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1911:
1912: if ($target ne 'helper') {
1913: return '';
1914: }
1915:
1916: my $contents = Apache::lonxml::get_all_text('/filefilter',
1917: $parser);
1918: $contents = 'sub { my $filename = shift; ' . $contents . '}';
1919: $paramHash->{FILTER_FUNC} = eval $contents;
1920: }
1921:
1922: sub end_filefilter { return ''; }
1.3 bowersj2 1923:
1924: sub render {
1925: my $self = shift;
1.5 bowersj2 1926: my $result = '';
1927: my $var = $self->{'variable'};
1928:
1929: my $subdirFunc = eval('sub {' . $self->{'filechoice'} . '}');
1.11 bowersj2 1930: die 'Error in resource filter code for variable ' .
1931: {'variable'} . ', Perl said:' . $@ if $@;
1932:
1.5 bowersj2 1933: my $subdir = &$subdirFunc();
1934:
1935: my $filterFunc = $self->{FILTER_FUNC};
1936: my $buttons = '';
1.22 bowersj2 1937: my $type = 'radio';
1938: if ($self->{'multichoice'}) {
1939: $type = 'checkbox';
1940: }
1.5 bowersj2 1941:
1942: if ($self->{'multichoice'}) {
1943: $result = <<SCRIPT;
1944: <script>
1.18 bowersj2 1945: function checkall(value, checkName) {
1.15 bowersj2 1946: for (i=0; i<document.forms.helpform.elements.length; i++) {
1947: ele = document.forms.helpform.elements[i];
1.18 bowersj2 1948: if (ele.name == checkName + '.forminput') {
1.15 bowersj2 1949: document.forms.helpform.elements[i].checked=value;
1.5 bowersj2 1950: }
1951: }
1952: }
1.21 bowersj2 1953:
1.22 bowersj2 1954: function checkallclass(value, className) {
1.21 bowersj2 1955: for (i=0; i<document.forms.helpform.elements.length; i++) {
1956: ele = document.forms.helpform.elements[i];
1.22 bowersj2 1957: if (ele.type == "$type" && ele.onclick) {
1.21 bowersj2 1958: document.forms.helpform.elements[i].checked=value;
1959: }
1960: }
1961: }
1.5 bowersj2 1962: </script>
1963: SCRIPT
1.15 bowersj2 1964: $buttons = <<BUTTONS;
1.5 bowersj2 1965: <br />
1.18 bowersj2 1966: <input type="button" onclick="checkall(true, '$var')" value="Select All Files" />
1967: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Files" />
1.23 bowersj2 1968: BUTTONS
1969:
1970: if ($helper->{VARS}->{'construction'}) {
1971: $buttons .= <<BUTTONS;
1.22 bowersj2 1972: <input type="button" onclick="checkallclass(true, 'Published')" value="Select All Published" />
1973: <input type="button" onclick="checkallclass(false, 'Published')" value="Unselect All Published" />
1.5 bowersj2 1974: <br />
1975: BUTTONS
1.23 bowersj2 1976: }
1.5 bowersj2 1977: }
1978:
1979: # Get the list of files in this directory.
1980: my @fileList;
1981:
1982: # If the subdirectory is in local CSTR space
1983: if ($subdir =~ m|/home/([^/]+)/public_html|) {
1984: my $user = $1;
1985: my $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
1986: @fileList = &Apache::lonnet::dirlist($subdir, $domain, $user, '');
1987: } else {
1988: # local library server resource space
1989: @fileList = &Apache::lonnet::dirlist($subdir, $ENV{'user.domain'}, $ENV{'user.name'}, '');
1990: }
1.3 bowersj2 1991:
1.5 bowersj2 1992: $result .= $buttons;
1993:
1.6 bowersj2 1994: if (defined $self->{ERROR_MSG}) {
1995: $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
1996: }
1997:
1.20 bowersj2 1998: $result .= '<table border="0" cellpadding="2" cellspacing="0">';
1.5 bowersj2 1999:
2000: # Keeps track if there are no choices, prints appropriate error
2001: # if there are none.
2002: my $choices = 0;
2003: # Print each legitimate file choice.
2004: for my $file (@fileList) {
2005: $file = (split(/&/, $file))[0];
2006: if ($file eq '.' || $file eq '..') {
2007: next;
2008: }
2009: my $fileName = $subdir .'/'. $file;
2010: if (&$filterFunc($file)) {
1.24 sakharuk 2011: my $status;
2012: my $color;
2013: if ($helper->{VARS}->{'construction'}) {
2014: ($status, $color) = @{fileState($subdir, $file)};
2015: } else {
2016: $status = '';
2017: $color = '';
2018: }
1.22 bowersj2 2019:
2020: # Netscape 4 is stupid and there's nowhere to put the
2021: # information on the input tag that the file is Published,
2022: # Unpublished, etc. In *real* browsers we can just say
2023: # "class='Published'" and check the className attribute of
2024: # the input tag, but Netscape 4 is too stupid to understand
2025: # that attribute, and un-comprehended attributes are not
2026: # reflected into the object model. So instead, what I do
2027: # is either have or don't have an "onclick" handler that
2028: # does nothing, give Published files the onclick handler, and
2029: # have the checker scripts check for that. Stupid and clumsy,
2030: # and only gives us binary "yes/no" information (at least I
2031: # couldn't figure out how to reach into the event handler's
2032: # actual code to retreive a value), but it works well enough
2033: # here.
1.23 bowersj2 2034:
1.22 bowersj2 2035: my $onclick = '';
1.23 bowersj2 2036: if ($status eq 'Published' && $helper->{VARS}->{'construction'}) {
1.22 bowersj2 2037: $onclick = 'onclick="a=1" ';
2038: }
1.20 bowersj2 2039: $result .= '<tr><td align="right"' . " bgcolor='$color'>" .
1.22 bowersj2 2040: "<input $onclick type='$type' name='" . $var
1.5 bowersj2 2041: . ".forminput' value='" . HTML::Entities::encode($fileName) .
2042: "'";
2043: if (!$self->{'multichoice'} && $choices == 0) {
2044: $result .= ' checked';
2045: }
1.20 bowersj2 2046: $result .= "/></td><td bgcolor='$color'>" . $file .
2047: "</td><td bgcolor='$color'>$status</td></tr>\n";
1.5 bowersj2 2048: $choices++;
2049: }
2050: }
2051:
2052: $result .= "</table>\n";
2053:
2054: if (!$choices) {
2055: $result .= '<font color="#FF0000">There are no files available to select in this directory. Please go back and select another option.</font><br /><br />';
2056: }
2057:
2058: $result .= $buttons;
2059:
2060: return $result;
1.20 bowersj2 2061: }
2062:
2063: # Determine the state of the file: Published, unpublished, modified.
2064: # Return the color it should be in and a label as a two-element array
2065: # reference.
2066: # Logic lifted from lonpubdir.pm, even though I don't know that it's still
2067: # the most right thing to do.
2068:
2069: sub fileState {
2070: my $constructionSpaceDir = shift;
2071: my $file = shift;
2072:
2073: my $docroot = $Apache::lonnet::perlvar{'lonDocRoot'};
2074: my $subdirpart = $constructionSpaceDir;
2075: $subdirpart =~ s/^\/home\/$ENV{'user.name'}\/public_html//;
2076: my $resdir = $docroot . '/res/' . $ENV{'user.domain'} . '/' . $ENV{'user.name'} .
2077: $subdirpart;
2078:
2079: my @constructionSpaceFileStat = stat($constructionSpaceDir . '/' . $file);
2080: my @resourceSpaceFileStat = stat($resdir . '/' . $file);
2081: if (!@resourceSpaceFileStat) {
2082: return ['Unpublished', '#FFCCCC'];
2083: }
2084:
2085: my $constructionSpaceFileModified = $constructionSpaceFileStat[9];
2086: my $resourceSpaceFileModified = $resourceSpaceFileStat[9];
2087:
2088: if ($constructionSpaceFileModified > $resourceSpaceFileModified) {
2089: return ['Modified', '#FFFFCC'];
2090: }
2091: return ['Published', '#CCFFCC'];
1.4 bowersj2 2092: }
1.5 bowersj2 2093:
1.4 bowersj2 2094: sub postprocess {
2095: my $self = shift;
1.6 bowersj2 2096: my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
2097: if (!$result) {
2098: $self->{ERROR_MSG} = 'You must choose at least one file '.
2099: 'to continue.';
2100: return 0;
2101: }
2102:
1.5 bowersj2 2103: if (defined($self->{NEXTSTATE})) {
2104: $helper->changeState($self->{NEXTSTATE});
1.3 bowersj2 2105: }
1.6 bowersj2 2106:
2107: return 1;
1.3 bowersj2 2108: }
1.8 bowersj2 2109:
2110: 1;
2111:
1.11 bowersj2 2112: package Apache::lonhelper::section;
2113:
2114: =pod
2115:
2116: =head2 Element: section
2117:
2118: <section> allows the user to choose one or more sections from the current
2119: course.
2120:
2121: It takes the standard attributes "variable", "multichoice", and
2122: "nextstate", meaning what they do for most other elements.
2123:
2124: =cut
2125:
2126: no strict;
2127: @ISA = ("Apache::lonhelper::choices");
2128: use strict;
2129:
2130: BEGIN {
2131: &Apache::lonhelper::register('Apache::lonhelper::section',
2132: ('section'));
2133: }
2134:
2135: sub new {
2136: my $ref = Apache::lonhelper::choices->new();
2137: bless($ref);
2138: }
2139:
2140: sub start_section {
2141: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2142:
2143: if ($target ne 'helper') {
2144: return '';
2145: }
1.12 bowersj2 2146:
2147: $paramHash->{CHOICES} = [];
2148:
1.11 bowersj2 2149: $paramHash->{'variable'} = $token->[2]{'variable'};
2150: $helper->declareVar($paramHash->{'variable'});
2151: $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
2152: if (defined($token->[2]{'nextstate'})) {
1.12 bowersj2 2153: $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
1.11 bowersj2 2154: }
2155:
2156: # Populate the CHOICES element
2157: my %choices;
2158:
2159: my $section = Apache::loncoursedata::CL_SECTION();
2160: my $classlist = Apache::loncoursedata::get_classlist();
2161: foreach (keys %$classlist) {
2162: my $sectionName = $classlist->{$_}->[$section];
2163: if (!$sectionName) {
2164: $choices{"No section assigned"} = "";
2165: } else {
2166: $choices{$sectionName} = $sectionName;
2167: }
1.12 bowersj2 2168: }
2169:
1.11 bowersj2 2170: for my $sectionName (sort(keys(%choices))) {
1.12 bowersj2 2171:
1.11 bowersj2 2172: push @{$paramHash->{CHOICES}}, [$sectionName, $sectionName];
2173: }
2174: }
2175:
1.12 bowersj2 2176: sub end_section {
2177: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.11 bowersj2 2178:
1.12 bowersj2 2179: if ($target ne 'helper') {
2180: return '';
2181: }
2182: Apache::lonhelper::section->new();
2183: }
1.11 bowersj2 2184: 1;
2185:
1.8 bowersj2 2186: package Apache::lonhelper::general;
2187:
2188: =pod
2189:
2190: =head2 General-purpose tag: <exec>
2191:
2192: The contents of the exec tag are executed as Perl code, not inside a
2193: safe space, so the full range of $ENV and such is available. The code
2194: will be executed as a subroutine wrapped with the following code:
2195:
2196: "sub { my $helper = shift; my $state = shift;" and
2197:
2198: "}"
2199:
2200: The return value is ignored.
2201:
2202: $helper is the helper object. Feel free to add methods to the helper
2203: object to support whatever manipulation you may need to do (for instance,
2204: overriding the form location if the state is the final state; see
2205: lonparm.helper for an example).
2206:
2207: $state is the $paramHash that has currently been generated and may
2208: be manipulated by the code in exec. Note that the $state is not yet
2209: an actual state B<object>, it is just a hash, so do not expect to
2210: be able to call methods on it.
2211:
2212: =cut
2213:
2214: BEGIN {
2215: &Apache::lonhelper::register('Apache::lonhelper::general',
1.11 bowersj2 2216: 'exec', 'condition', 'clause',
2217: 'eval');
1.8 bowersj2 2218: }
2219:
2220: sub start_exec {
2221: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2222:
2223: if ($target ne 'helper') {
2224: return '';
2225: }
2226:
2227: my $code = &Apache::lonxml::get_all_text('/exec', $parser);
2228:
2229: $code = eval ('sub { my $helper = shift; my $state = shift; ' .
2230: $code . "}");
1.11 bowersj2 2231: die 'Error in <exec>, Perl said: '. $@ if $@;
1.8 bowersj2 2232: &$code($helper, $paramHash);
2233: }
2234:
2235: sub end_exec { return ''; }
2236:
2237: =pod
2238:
2239: =head2 General-purpose tag: <condition>
2240:
2241: The <condition> tag allows you to mask out parts of the helper code
2242: depending on some programatically determined condition. The condition
2243: tag contains a tag <clause> which contains perl code that when wrapped
2244: with "sub { my $helper = shift; my $state = shift; " and "}", returns
2245: a true value if the XML in the condition should be evaluated as a normal
2246: part of the helper, or false if it should be completely discarded.
2247:
2248: The <clause> tag must be the first sub-tag of the <condition> tag or
2249: it will not work as expected.
2250:
2251: =cut
2252:
2253: # The condition tag just functions as a marker, it doesn't have
2254: # to "do" anything. Technically it doesn't even have to be registered
2255: # with the lonxml code, but I leave this here to be explicit about it.
2256: sub start_condition { return ''; }
2257: sub end_condition { return ''; }
2258:
2259: sub start_clause {
2260: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2261:
2262: if ($target ne 'helper') {
2263: return '';
2264: }
2265:
2266: my $clause = Apache::lonxml::get_all_text('/clause', $parser);
2267: $clause = eval('sub { my $helper = shift; my $state = shift; '
2268: . $clause . '}');
1.11 bowersj2 2269: die 'Error in clause of condition, Perl said: ' . $@ if $@;
1.8 bowersj2 2270: if (!&$clause($helper, $paramHash)) {
2271: # Discard all text until the /condition.
2272: &Apache::lonxml::get_all_text('/condition', $parser);
2273: }
2274: }
2275:
2276: sub end_clause { return ''; }
1.11 bowersj2 2277:
2278: =pod
2279:
2280: =head2 General-purpose tag: <eval>
2281:
2282: The <eval> tag will be evaluated as a subroutine call passed in the
2283: current helper object and state hash as described in <condition> above,
2284: but is expected to return a string to be printed directly to the
2285: screen. This is useful for dynamically generating messages.
2286:
2287: =cut
2288:
2289: # This is basically a type of message.
2290: # Programmatically setting $paramHash->{NEXTSTATE} would work, though
2291: # it's probably bad form.
2292:
2293: sub start_eval {
2294: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2295:
2296: if ($target ne 'helper') {
2297: return '';
2298: }
2299:
2300: my $program = Apache::lonxml::get_all_text('/eval', $parser);
2301: $program = eval('sub { my $helper = shift; my $state = shift; '
2302: . $program . '}');
2303: die 'Error in eval code, Perl said: ' . $@ if $@;
2304: $paramHash->{MESSAGE_TEXT} = &$program($helper, $paramHash);
2305: }
2306:
2307: sub end_eval {
2308: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2309:
2310: if ($target ne 'helper') {
2311: return '';
2312: }
2313:
2314: Apache::lonhelper::message->new();
2315: }
2316:
1.13 bowersj2 2317: 1;
2318:
1.27 bowersj2 2319: package Apache::lonhelper::final;
2320:
2321: =pod
2322:
2323: =head2 Element: final
2324:
2325: <final> is a special element that works with helpers that use the <finalcode>
2326: tag. It goes through all the states and elements, executing the <finalcode>
2327: snippets and collecting the results. Finally, it takes the user out of the
2328: helper, going to a provided page.
2329:
2330: =cut
2331:
2332: no strict;
2333: @ISA = ("Apache::lonhelper::element");
2334: use strict;
2335:
2336: BEGIN {
2337: &Apache::lonhelper::register('Apache::lonhelper::final',
2338: ('final', 'exitpage'));
2339: }
2340:
2341: sub new {
2342: my $ref = Apache::lonhelper::element->new();
2343: bless($ref);
2344: }
2345:
2346: sub start_final { return ''; }
2347:
2348: sub end_final {
2349: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2350:
2351: if ($target ne 'helper') {
2352: return '';
2353: }
2354:
2355: Apache::lonhelper::final->new();
2356:
2357: return '';
2358: }
2359:
2360: sub start_exitpage {
2361: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2362:
2363: if ($target ne 'helper') {
2364: return '';
2365: }
2366:
2367: $paramHash->{EXIT_PAGE} = &Apache::lonxml::get_all_text('/exitpage',
2368: $parser);
2369:
2370: return '';
2371: }
2372:
2373: sub end_exitpage { return ''; }
2374:
2375: sub render {
2376: my $self = shift;
2377:
2378: my @results;
2379:
2380: # Collect all the results
2381: for my $stateName (keys %{$helper->{STATES}}) {
2382: my $state = $helper->{STATES}->{$stateName};
2383:
2384: for my $element (@{$state->{ELEMENTS}}) {
2385: if (defined($element->{FINAL_CODE})) {
2386: # Compile the code.
2387: my $code = 'sub { my $helper = shift; ' . $element->{FINAL_CODE} .
2388: '}';
2389: $code = eval($code);
2390: die 'Error while executing final code for element with var ' .
2391: $element->{'variable'} . ', Perl said: ' . $@ if $@;
2392:
2393: my $result = &$code($helper);
2394: if ($result) {
2395: push @results, $result;
2396: }
2397: }
2398: }
2399: }
2400:
2401: if (scalar(@results) == 0) {
2402: return '';
2403: }
2404:
2405: my $result = "<ul>\n";
2406: for my $re (@results) {
2407: $result .= ' <li>' . $re . "</li>\n";
2408: }
2409: return $result . '</ul>';
2410: }
2411:
2412: 1;
2413:
1.13 bowersj2 2414: package Apache::lonhelper::parmwizfinal;
2415:
2416: # This is the final state for the parmwizard. It is not generally useful,
2417: # so it is not perldoc'ed. It does its own processing.
2418: # It is represented with <parmwizfinal />, and
2419: # should later be moved to lonparmset.pm .
2420:
2421: no strict;
2422: @ISA = ('Apache::lonhelper::element');
2423: use strict;
1.11 bowersj2 2424:
1.13 bowersj2 2425: BEGIN {
2426: &Apache::lonhelper::register('Apache::lonhelper::parmwizfinal',
2427: ('parmwizfinal'));
2428: }
2429:
2430: use Time::localtime;
2431:
2432: sub new {
2433: my $ref = Apache::lonhelper::choices->new();
2434: bless ($ref);
2435: }
2436:
2437: sub start_parmwizfinal { return ''; }
2438:
2439: sub end_parmwizfinal {
2440: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2441:
2442: if ($target ne 'helper') {
2443: return '';
2444: }
2445: Apache::lonhelper::parmwizfinal->new();
2446: }
2447:
2448: # Renders a form that, when submitted, will form the input to lonparmset.pm
2449: sub render {
2450: my $self = shift;
2451: my $vars = $helper->{VARS};
2452:
2453: # FIXME: Unify my designators with the standard ones
2454: my %dateTypeHash = ('open_date' => "Opening Date",
2455: 'due_date' => "Due Date",
2456: 'answer_date' => "Answer Date");
2457: my %parmTypeHash = ('open_date' => "0_opendate",
2458: 'due_date' => "0_duedate",
2459: 'answer_date' => "0_answerdate");
2460:
2461: my $affectedResourceId = "";
2462: my $parm_name = $parmTypeHash{$vars->{ACTION_TYPE}};
2463: my $level = "";
1.27 bowersj2 2464: my $resourceString;
2465: my $symb;
2466: my $paramlevel;
2467:
1.13 bowersj2 2468: # Print the granularity, depending on the action
2469: if ($vars->{GRANULARITY} eq 'whole_course') {
1.27 bowersj2 2470: $resourceString .= '<li>for <b>all resources in the course</b></li>';
1.13 bowersj2 2471: $level = 9; # general course, see lonparmset.pm perldoc
2472: $affectedResourceId = "0.0";
1.27 bowersj2 2473: $symb = 'a';
2474: $paramlevel = 'general';
1.13 bowersj2 2475: } elsif ($vars->{GRANULARITY} eq 'map') {
2476: my $navmap = Apache::lonnavmaps::navmap->new(
2477: $ENV{"request.course.fn"}.".db",
2478: $ENV{"request.course.fn"}."_parms.db", 0, 0);
2479: my $res = $navmap->getById($vars->{RESOURCE_ID});
2480: my $title = $res->compTitle();
1.27 bowersj2 2481: $symb = $res->symb();
1.13 bowersj2 2482: $navmap->untieHashes();
1.27 bowersj2 2483: $resourceString .= "<li>for the map named <b>$title</b></li>";
1.13 bowersj2 2484: $level = 8;
2485: $affectedResourceId = $vars->{RESOURCE_ID};
1.27 bowersj2 2486: $paramlevel = 'map';
1.13 bowersj2 2487: } else {
2488: my $navmap = Apache::lonnavmaps::navmap->new(
2489: $ENV{"request.course.fn"}.".db",
2490: $ENV{"request.course.fn"}."_parms.db", 0, 0);
2491: my $res = $navmap->getById($vars->{RESOURCE_ID});
1.27 bowersj2 2492: $symb = $res->symb();
1.13 bowersj2 2493: my $title = $res->compTitle();
2494: $navmap->untieHashes();
1.27 bowersj2 2495: $resourceString .= "<li>for the resource named <b>$title</b></li>";
1.13 bowersj2 2496: $level = 7;
2497: $affectedResourceId = $vars->{RESOURCE_ID};
1.27 bowersj2 2498: $paramlevel = 'full';
1.13 bowersj2 2499: }
2500:
1.27 bowersj2 2501: my $result = "<form name='helpform' method='get' action='/adm/parmset#$affectedResourceId&$parm_name&$level'>\n";
2502: $result .= '<p>Confirm that this information is correct, then click "Finish Wizard" to complete setting the parameter.<ul>';
2503:
2504: # Print the type of manipulation:
2505: $result .= '<li>Setting the <b>' . $dateTypeHash{$vars->{ACTION_TYPE}}
2506: . "</b></li>\n";
2507: if ($vars->{ACTION_TYPE} eq 'due_date' ||
2508: $vars->{ACTION_TYPE} eq 'answer_date') {
2509: # for due dates, we default to "date end" type entries
2510: $result .= "<input type='hidden' name='recent_date_end' " .
2511: "value='" . $vars->{PARM_DATE} . "' />\n";
2512: $result .= "<input type='hidden' name='pres_value' " .
2513: "value='" . $vars->{PARM_DATE} . "' />\n";
2514: $result .= "<input type='hidden' name='pres_type' " .
2515: "value='date_end' />\n";
2516: } elsif ($vars->{ACTION_TYPE} eq 'open_date') {
2517: $result .= "<input type='hidden' name='recent_date_start' ".
2518: "value='" . $vars->{PARM_DATE} . "' />\n";
2519: $result .= "<input type='hidden' name='pres_value' " .
2520: "value='" . $vars->{PARM_DATE} . "' />\n";
2521: $result .= "<input type='hidden' name='pres_type' " .
2522: "value='date_start' />\n";
2523: }
2524:
2525: $result .= $resourceString;
2526:
1.13 bowersj2 2527: # Print targets
2528: if ($vars->{TARGETS} eq 'course') {
2529: $result .= '<li>for <b>all students in course</b></li>';
2530: } elsif ($vars->{TARGETS} eq 'section') {
2531: my $section = $vars->{SECTION_NAME};
2532: $result .= "<li>for section <b>$section</b></li>";
2533: $level -= 3;
2534: $result .= "<input type='hidden' name='csec' value='" .
2535: HTML::Entities::encode($section) . "' />\n";
2536: } else {
2537: # FIXME: This is probably wasteful! Store the name!
2538: my $classlist = Apache::loncoursedata::get_classlist();
1.27 bowersj2 2539: my $username = $vars->{USER_NAME};
2540: # Chop off everything after the last colon (section)
2541: $username = substr($username, 0, rindex($username, ':'));
2542: my $name = $classlist->{$username}->[6];
1.13 bowersj2 2543: $result .= "<li>for <b>$name</b></li>";
2544: $level -= 6;
2545: my ($uname, $udom) = split /:/, $vars->{USER_NAME};
2546: $result .= "<input type='hidden' name='uname' value='".
2547: HTML::Entities::encode($uname) . "' />\n";
2548: $result .= "<input type='hidden' name='udom' value='".
2549: HTML::Entities::encode($udom) . "' />\n";
2550: }
2551:
2552: # Print value
2553: $result .= "<li>to <b>" . ctime($vars->{PARM_DATE}) . "</b> (" .
2554: Apache::lonnavmaps::timeToHumanString($vars->{PARM_DATE})
2555: . ")</li>\n";
2556:
2557: # print pres_marker
2558: $result .= "\n<input type='hidden' name='pres_marker'" .
2559: " value='$affectedResourceId&$parm_name&$level' />\n";
1.27 bowersj2 2560:
2561: # Make the table appear
2562: $result .= "\n<input type='hidden' value='true' name='prevvisit' />";
2563: $result .= "\n<input type='hidden' value='all' name='pschp' />";
2564: $result .= "\n<input type='hidden' value='$symb' name='pssymb' />";
2565: $result .= "\n<input type='hidden' value='$paramlevel' name='parmlev' />";
1.13 bowersj2 2566:
2567: $result .= "<br /><br /><center><input type='submit' value='Finish Helper' /></center></form>\n";
2568:
2569: return $result;
2570: }
2571:
2572: sub overrideForm {
2573: return 1;
2574: }
1.5 bowersj2 2575:
1.4 bowersj2 2576: 1;
1.3 bowersj2 2577:
1.1 bowersj2 2578: __END__
1.3 bowersj2 2579:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>