Annotation of loncom/interface/lonhelper.pm, revision 1.29
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
1.29 ! bowersj2 1422: to false. The "suppressEmptySequences" attribute reflects the
! 1423: suppressEmptySequences argument to the render routine, which will cause
! 1424: folders that have all of their contained resources filtered out to also
! 1425: be filtered out.
1.5 bowersj2 1426:
1427: B<SUB-TAGS>
1428:
1429: =over 4
1430:
1431: =item * <filterfunc>: If you want to filter what resources are displayed
1432: to the user, use a filter func. The <filterfunc> tag should contain
1433: Perl code that when wrapped with "sub { my $res = shift; " and "}" is
1434: a function that returns true if the resource should be displayed,
1435: and false if it should be skipped. $res is a resource object.
1436: (See Apache::lonnavmaps documentation for information about the
1437: resource object.)
1438:
1439: =item * <choicefunc>: Same as <filterfunc>, except that controls whether
1440: the given resource can be chosen. (It is almost always a good idea to
1441: show the user the folders, for instance, but you do not always want to
1442: let the user select them.)
1443:
1444: =item * <nextstate>: Standard nextstate behavior.
1445:
1446: =item * <valuefunc>: This function controls what is returned by the resource
1447: when the user selects it. Like filterfunc and choicefunc, it should be
1448: a function fragment that when wrapped by "sub { my $res = shift; " and
1449: "}" returns a string representing what you want to have as the value. By
1450: default, the value will be the resource ID of the object ($res->{ID}).
1451:
1.13 bowersj2 1452: =item * <mapurl>: If the URL of a map is given here, only that map
1453: will be displayed, instead of the whole course.
1454:
1.5 bowersj2 1455: =back
1456:
1457: =cut
1458:
1459: no strict;
1460: @ISA = ("Apache::lonhelper::element");
1461: use strict;
1462:
1463: BEGIN {
1.7 bowersj2 1464: &Apache::lonhelper::register('Apache::lonhelper::resource',
1.5 bowersj2 1465: ('resource', 'filterfunc',
1.13 bowersj2 1466: 'choicefunc', 'valuefunc',
1467: 'mapurl'));
1.5 bowersj2 1468: }
1469:
1470: sub new {
1471: my $ref = Apache::lonhelper::element->new();
1472: bless($ref);
1473: }
1474:
1475: # CONSTRUCTION: Construct the message element from the XML
1476: sub start_resource {
1477: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1478:
1479: if ($target ne 'helper') {
1480: return '';
1481: }
1482:
1483: $paramHash->{'variable'} = $token->[2]{'variable'};
1484: $helper->declareVar($paramHash->{'variable'});
1.14 bowersj2 1485: $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.29 ! bowersj2 1486: $paramHash->{'suppressEmptySequences'} = $token->[2]{'suppressEmptySequences'};
1.17 bowersj2 1487: $paramHash->{'toponly'} = $token->[2]{'toponly'};
1.5 bowersj2 1488: return '';
1489: }
1490:
1491: sub end_resource {
1492: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1493:
1494: if ($target ne 'helper') {
1495: return '';
1496: }
1497: if (!defined($paramHash->{FILTER_FUNC})) {
1498: $paramHash->{FILTER_FUNC} = sub {return 1;};
1499: }
1500: if (!defined($paramHash->{CHOICE_FUNC})) {
1501: $paramHash->{CHOICE_FUNC} = sub {return 1;};
1502: }
1503: if (!defined($paramHash->{VALUE_FUNC})) {
1504: $paramHash->{VALUE_FUNC} = sub {my $res = shift; return $res->{ID}; };
1505: }
1506: Apache::lonhelper::resource->new();
1.4 bowersj2 1507: return '';
1508: }
1509:
1.5 bowersj2 1510: sub start_filterfunc {
1511: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1512:
1513: if ($target ne 'helper') {
1514: return '';
1515: }
1516:
1517: my $contents = Apache::lonxml::get_all_text('/filterfunc',
1518: $parser);
1519: $contents = 'sub { my $res = shift; ' . $contents . '}';
1520: $paramHash->{FILTER_FUNC} = eval $contents;
1521: }
1522:
1523: sub end_filterfunc { return ''; }
1524:
1525: sub start_choicefunc {
1526: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1527:
1528: if ($target ne 'helper') {
1529: return '';
1530: }
1531:
1532: my $contents = Apache::lonxml::get_all_text('/choicefunc',
1533: $parser);
1534: $contents = 'sub { my $res = shift; ' . $contents . '}';
1535: $paramHash->{CHOICE_FUNC} = eval $contents;
1536: }
1537:
1538: sub end_choicefunc { return ''; }
1539:
1540: sub start_valuefunc {
1541: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1542:
1543: if ($target ne 'helper') {
1544: return '';
1545: }
1546:
1547: my $contents = Apache::lonxml::get_all_text('/valuefunc',
1548: $parser);
1549: $contents = 'sub { my $res = shift; ' . $contents . '}';
1550: $paramHash->{VALUE_FUNC} = eval $contents;
1551: }
1552:
1553: sub end_valuefunc { return ''; }
1554:
1.13 bowersj2 1555: sub start_mapurl {
1556: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1557:
1558: if ($target ne 'helper') {
1559: return '';
1560: }
1561:
1562: my $contents = Apache::lonxml::get_all_text('/mapurl',
1563: $parser);
1.14 bowersj2 1564: $paramHash->{MAP_URL} = $contents;
1.13 bowersj2 1565: }
1566:
1567: sub end_mapurl { return ''; }
1568:
1.5 bowersj2 1569: # A note, in case I don't get to this before I leave.
1570: # If someone complains about the "Back" button returning them
1571: # to the previous folder state, instead of returning them to
1572: # the previous helper state, the *correct* answer is for the helper
1573: # to keep track of how many times the user has manipulated the folders,
1574: # and feed that to the history.go() call in the helper rendering routines.
1575: # If done correctly, the helper itself can keep track of how many times
1576: # it renders the same states, so it doesn't go in just this state, and
1577: # you can lean on the browser back button to make sure it all chains
1578: # correctly.
1579: # Right now, though, I'm just forcing all folders open.
1580:
1581: sub render {
1582: my $self = shift;
1583: my $result = "";
1584: my $var = $self->{'variable'};
1585: my $curVal = $helper->{VARS}->{$var};
1586:
1.15 bowersj2 1587: my $buttons = '';
1588:
1589: if ($self->{'multichoice'}) {
1590: $result = <<SCRIPT;
1591: <script>
1.18 bowersj2 1592: function checkall(value, checkName) {
1.15 bowersj2 1593: for (i=0; i<document.forms.helpform.elements.length; i++) {
1594: ele = document.forms.helpform.elements[i];
1.18 bowersj2 1595: if (ele.name == checkName + '.forminput') {
1.15 bowersj2 1596: document.forms.helpform.elements[i].checked=value;
1597: }
1598: }
1599: }
1600: </script>
1601: SCRIPT
1602: $buttons = <<BUTTONS;
1603: <br />
1.18 bowersj2 1604: <input type="button" onclick="checkall(true, '$var')" value="Select All Resources" />
1605: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Resources" />
1.15 bowersj2 1606: <br />
1607: BUTTONS
1608: }
1609:
1.5 bowersj2 1610: if (defined $self->{ERROR_MSG}) {
1.14 bowersj2 1611: $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
1.5 bowersj2 1612: }
1613:
1.15 bowersj2 1614: $result .= $buttons;
1615:
1.5 bowersj2 1616: my $filterFunc = $self->{FILTER_FUNC};
1617: my $choiceFunc = $self->{CHOICE_FUNC};
1618: my $valueFunc = $self->{VALUE_FUNC};
1.13 bowersj2 1619: my $mapUrl = $self->{MAP_URL};
1.14 bowersj2 1620: my $multichoice = $self->{'multichoice'};
1.5 bowersj2 1621:
1622: # Create the composite function that renders the column on the nav map
1623: # have to admit any language that lets me do this can't be all bad
1624: # - Jeremy (Pythonista) ;-)
1625: my $checked = 0;
1626: my $renderColFunc = sub {
1627: my ($resource, $part, $params) = @_;
1.14 bowersj2 1628:
1629: my $inputType;
1630: if ($multichoice) { $inputType = 'checkbox'; }
1631: else {$inputType = 'radio'; }
1632:
1.5 bowersj2 1633: if (!&$choiceFunc($resource)) {
1634: return '<td> </td>';
1635: } else {
1.14 bowersj2 1636: my $col = "<td><input type='$inputType' name='${var}.forminput' ";
1637: if (!$checked && !$multichoice) {
1.5 bowersj2 1638: $col .= "checked ";
1639: $checked = 1;
1640: }
1641: $col .= "value='" .
1642: HTML::Entities::encode(&$valueFunc($resource))
1643: . "' /></td>";
1644: return $col;
1645: }
1646: };
1647:
1.17 bowersj2 1648: $ENV{'form.condition'} = !$self->{'toponly'};
1.5 bowersj2 1649: $result .=
1650: &Apache::lonnavmaps::render( { 'cols' => [$renderColFunc,
1651: Apache::lonnavmaps::resource()],
1652: 'showParts' => 0,
1653: 'filterFunc' => $filterFunc,
1.13 bowersj2 1654: 'resource_no_folder_link' => 1,
1.29 ! bowersj2 1655: 'suppressEmptySequences' => $self->{'suppressEmptySequences'},
1.13 bowersj2 1656: 'iterator_map' => $mapUrl }
1.5 bowersj2 1657: );
1.15 bowersj2 1658:
1659: $result .= $buttons;
1.5 bowersj2 1660:
1661: return $result;
1662: }
1663:
1664: sub postprocess {
1665: my $self = shift;
1.14 bowersj2 1666:
1667: if ($self->{'multichoice'} && !$helper->{VARS}->{$self->{'variable'}}) {
1668: $self->{ERROR_MSG} = 'You must choose at least one resource to continue.';
1669: return 0;
1670: }
1671:
1.5 bowersj2 1672: if (defined($self->{NEXTSTATE})) {
1673: $helper->changeState($self->{NEXTSTATE});
1674: }
1.6 bowersj2 1675:
1676: return 1;
1.5 bowersj2 1677: }
1678:
1679: 1;
1680:
1681: package Apache::lonhelper::student;
1682:
1683: =pod
1684:
1685: =head2 Element: student
1686:
1687: Student elements display a choice of students enrolled in the current
1688: course. Currently it is primitive; this is expected to evolve later.
1689:
1690: Student elements take two attributes: "variable", which means what
1691: it usually does, and "multichoice", which if true allows the user
1692: to select multiple students.
1693:
1694: =cut
1695:
1696: no strict;
1697: @ISA = ("Apache::lonhelper::element");
1698: use strict;
1699:
1700:
1701:
1702: BEGIN {
1.7 bowersj2 1703: &Apache::lonhelper::register('Apache::lonhelper::student',
1.5 bowersj2 1704: ('student'));
1705: }
1706:
1707: sub new {
1708: my $ref = Apache::lonhelper::element->new();
1709: bless($ref);
1710: }
1.4 bowersj2 1711:
1.5 bowersj2 1712: sub start_student {
1.4 bowersj2 1713: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1714:
1715: if ($target ne 'helper') {
1716: return '';
1717: }
1718:
1.5 bowersj2 1719: $paramHash->{'variable'} = $token->[2]{'variable'};
1720: $helper->declareVar($paramHash->{'variable'});
1721: $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.12 bowersj2 1722: if (defined($token->[2]{'nextstate'})) {
1723: $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
1724: }
1725:
1.5 bowersj2 1726: }
1727:
1728: sub end_student {
1729: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1730:
1731: if ($target ne 'helper') {
1732: return '';
1733: }
1734: Apache::lonhelper::student->new();
1.3 bowersj2 1735: }
1.5 bowersj2 1736:
1737: sub render {
1738: my $self = shift;
1739: my $result = '';
1740: my $buttons = '';
1.18 bowersj2 1741: my $var = $self->{'variable'};
1.5 bowersj2 1742:
1743: if ($self->{'multichoice'}) {
1744: $result = <<SCRIPT;
1745: <script>
1.18 bowersj2 1746: function checkall(value, checkName) {
1.15 bowersj2 1747: for (i=0; i<document.forms.helpform.elements.length; i++) {
1.18 bowersj2 1748: ele = document.forms.helpform.elements[i];
1749: if (ele.name == checkName + '.forminput') {
1750: document.forms.helpform.elements[i].checked=value;
1751: }
1.5 bowersj2 1752: }
1753: }
1754: </script>
1755: SCRIPT
1756: $buttons = <<BUTTONS;
1757: <br />
1.18 bowersj2 1758: <input type="button" onclick="checkall(true, '$var')" value="Select All Students" />
1759: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Students" />
1.5 bowersj2 1760: <br />
1761: BUTTONS
1762: }
1763:
1764: if (defined $self->{ERROR_MSG}) {
1765: $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
1766: }
1767:
1768: # Load up the students
1769: my $choices = &Apache::loncoursedata::get_classlist();
1770: my @keys = keys %{$choices};
1771:
1772: # Constants
1773: my $section = Apache::loncoursedata::CL_SECTION();
1774: my $fullname = Apache::loncoursedata::CL_FULLNAME();
1775:
1776: # Sort by: Section, name
1777: @keys = sort {
1778: if ($choices->{$a}->[$section] ne $choices->{$b}->[$section]) {
1779: return $choices->{$a}->[$section] cmp $choices->{$b}->[$section];
1780: }
1781: return $choices->{$a}->[$fullname] cmp $choices->{$b}->[$fullname];
1782: } @keys;
1783:
1784: my $type = 'radio';
1785: if ($self->{'multichoice'}) { $type = 'checkbox'; }
1786: $result .= "<table cellspacing='2' cellpadding='2' border='0'>\n";
1787: $result .= "<tr><td></td><td align='center'><b>Student Name</b></td>".
1788: "<td align='center'><b>Section</b></td></tr>";
1789:
1790: my $checked = 0;
1791: foreach (@keys) {
1792: $result .= "<tr><td><input type='$type' name='" .
1793: $self->{'variable'} . '.forminput' . "'";
1794:
1795: if (!$self->{'multichoice'} && !$checked) {
1796: $result .= " checked ";
1797: $checked = 1;
1798: }
1799: $result .=
1.19 bowersj2 1800: " value='" . HTML::Entities::encode($_ . ':' . $choices->{$_}->[$section])
1.5 bowersj2 1801: . "' /></td><td>"
1802: . HTML::Entities::encode($choices->{$_}->[$fullname])
1803: . "</td><td align='center'>"
1804: . HTML::Entities::encode($choices->{$_}->[$section])
1805: . "</td></tr>\n";
1806: }
1807:
1808: $result .= "</table>\n\n";
1809: $result .= $buttons;
1.4 bowersj2 1810:
1.5 bowersj2 1811: return $result;
1812: }
1813:
1.6 bowersj2 1814: sub postprocess {
1815: my $self = shift;
1816:
1817: my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
1818: if (!$result) {
1819: $self->{ERROR_MSG} = 'You must choose at least one student '.
1820: 'to continue.';
1821: return 0;
1822: }
1823:
1824: if (defined($self->{NEXTSTATE})) {
1825: $helper->changeState($self->{NEXTSTATE});
1826: }
1827:
1828: return 1;
1829: }
1830:
1.5 bowersj2 1831: 1;
1832:
1833: package Apache::lonhelper::files;
1834:
1835: =pod
1836:
1837: =head2 Element: files
1838:
1839: files allows the users to choose files from a given directory on the
1840: server. It is always multichoice and stores the result as a triple-pipe
1841: delimited entry in the helper variables.
1842:
1843: Since it is extremely unlikely that you can actually code a constant
1844: representing the directory you wish to allow the user to search, <files>
1845: takes a subroutine that returns the name of the directory you wish to
1846: have the user browse.
1847:
1848: files accepts the attribute "variable" to control where the files chosen
1849: are put. It accepts the attribute "multichoice" as the other attribute,
1850: defaulting to false, which if true will allow the user to select more
1851: then one choice.
1852:
1853: <files> accepts three subtags. One is the "nextstate" sub-tag that works
1854: as it does with the other tags. Another is a <filechoice> sub tag that
1855: is Perl code that, when surrounded by "sub {" and "}" will return a
1856: string representing what directory on the server to allow the user to
1857: choose files from. Finally, the <filefilter> subtag should contain Perl
1858: code that when surrounded by "sub { my $filename = shift; " and "}",
1859: returns a true value if the user can pick that file, or false otherwise.
1860: The filename passed to the function will be just the name of the file,
1861: with no path info.
1862:
1863: =cut
1864:
1865: no strict;
1866: @ISA = ("Apache::lonhelper::element");
1867: use strict;
1868:
1869: BEGIN {
1.7 bowersj2 1870: &Apache::lonhelper::register('Apache::lonhelper::files',
1871: ('files', 'filechoice', 'filefilter'));
1.5 bowersj2 1872: }
1873:
1874: sub new {
1875: my $ref = Apache::lonhelper::element->new();
1876: bless($ref);
1877: }
1878:
1879: sub start_files {
1880: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1881:
1882: if ($target ne 'helper') {
1883: return '';
1884: }
1885: $paramHash->{'variable'} = $token->[2]{'variable'};
1886: $helper->declareVar($paramHash->{'variable'});
1887: $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1888: }
1889:
1890: sub end_files {
1891: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1892:
1893: if ($target ne 'helper') {
1894: return '';
1895: }
1896: if (!defined($paramHash->{FILTER_FUNC})) {
1897: $paramHash->{FILTER_FUNC} = sub { return 1; };
1898: }
1899: Apache::lonhelper::files->new();
1900: }
1901:
1902: sub start_filechoice {
1903: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1904:
1905: if ($target ne 'helper') {
1906: return '';
1907: }
1908: $paramHash->{'filechoice'} = Apache::lonxml::get_all_text('/filechoice',
1909: $parser);
1910: }
1911:
1912: sub end_filechoice { return ''; }
1913:
1914: sub start_filefilter {
1915: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1916:
1917: if ($target ne 'helper') {
1918: return '';
1919: }
1920:
1921: my $contents = Apache::lonxml::get_all_text('/filefilter',
1922: $parser);
1923: $contents = 'sub { my $filename = shift; ' . $contents . '}';
1924: $paramHash->{FILTER_FUNC} = eval $contents;
1925: }
1926:
1927: sub end_filefilter { return ''; }
1.3 bowersj2 1928:
1929: sub render {
1930: my $self = shift;
1.5 bowersj2 1931: my $result = '';
1932: my $var = $self->{'variable'};
1933:
1934: my $subdirFunc = eval('sub {' . $self->{'filechoice'} . '}');
1.11 bowersj2 1935: die 'Error in resource filter code for variable ' .
1936: {'variable'} . ', Perl said:' . $@ if $@;
1937:
1.5 bowersj2 1938: my $subdir = &$subdirFunc();
1939:
1940: my $filterFunc = $self->{FILTER_FUNC};
1941: my $buttons = '';
1.22 bowersj2 1942: my $type = 'radio';
1943: if ($self->{'multichoice'}) {
1944: $type = 'checkbox';
1945: }
1.5 bowersj2 1946:
1947: if ($self->{'multichoice'}) {
1948: $result = <<SCRIPT;
1949: <script>
1.18 bowersj2 1950: function checkall(value, checkName) {
1.15 bowersj2 1951: for (i=0; i<document.forms.helpform.elements.length; i++) {
1952: ele = document.forms.helpform.elements[i];
1.18 bowersj2 1953: if (ele.name == checkName + '.forminput') {
1.15 bowersj2 1954: document.forms.helpform.elements[i].checked=value;
1.5 bowersj2 1955: }
1956: }
1957: }
1.21 bowersj2 1958:
1.22 bowersj2 1959: function checkallclass(value, className) {
1.21 bowersj2 1960: for (i=0; i<document.forms.helpform.elements.length; i++) {
1961: ele = document.forms.helpform.elements[i];
1.22 bowersj2 1962: if (ele.type == "$type" && ele.onclick) {
1.21 bowersj2 1963: document.forms.helpform.elements[i].checked=value;
1964: }
1965: }
1966: }
1.5 bowersj2 1967: </script>
1968: SCRIPT
1.15 bowersj2 1969: $buttons = <<BUTTONS;
1.5 bowersj2 1970: <br />
1.18 bowersj2 1971: <input type="button" onclick="checkall(true, '$var')" value="Select All Files" />
1972: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Files" />
1.23 bowersj2 1973: BUTTONS
1974:
1975: if ($helper->{VARS}->{'construction'}) {
1976: $buttons .= <<BUTTONS;
1.22 bowersj2 1977: <input type="button" onclick="checkallclass(true, 'Published')" value="Select All Published" />
1978: <input type="button" onclick="checkallclass(false, 'Published')" value="Unselect All Published" />
1.5 bowersj2 1979: <br />
1980: BUTTONS
1.23 bowersj2 1981: }
1.5 bowersj2 1982: }
1983:
1984: # Get the list of files in this directory.
1985: my @fileList;
1986:
1987: # If the subdirectory is in local CSTR space
1988: if ($subdir =~ m|/home/([^/]+)/public_html|) {
1989: my $user = $1;
1990: my $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
1991: @fileList = &Apache::lonnet::dirlist($subdir, $domain, $user, '');
1992: } else {
1993: # local library server resource space
1994: @fileList = &Apache::lonnet::dirlist($subdir, $ENV{'user.domain'}, $ENV{'user.name'}, '');
1995: }
1.3 bowersj2 1996:
1.5 bowersj2 1997: $result .= $buttons;
1998:
1.6 bowersj2 1999: if (defined $self->{ERROR_MSG}) {
2000: $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
2001: }
2002:
1.20 bowersj2 2003: $result .= '<table border="0" cellpadding="2" cellspacing="0">';
1.5 bowersj2 2004:
2005: # Keeps track if there are no choices, prints appropriate error
2006: # if there are none.
2007: my $choices = 0;
2008: # Print each legitimate file choice.
2009: for my $file (@fileList) {
2010: $file = (split(/&/, $file))[0];
2011: if ($file eq '.' || $file eq '..') {
2012: next;
2013: }
2014: my $fileName = $subdir .'/'. $file;
2015: if (&$filterFunc($file)) {
1.24 sakharuk 2016: my $status;
2017: my $color;
2018: if ($helper->{VARS}->{'construction'}) {
2019: ($status, $color) = @{fileState($subdir, $file)};
2020: } else {
2021: $status = '';
2022: $color = '';
2023: }
1.22 bowersj2 2024:
2025: # Netscape 4 is stupid and there's nowhere to put the
2026: # information on the input tag that the file is Published,
2027: # Unpublished, etc. In *real* browsers we can just say
2028: # "class='Published'" and check the className attribute of
2029: # the input tag, but Netscape 4 is too stupid to understand
2030: # that attribute, and un-comprehended attributes are not
2031: # reflected into the object model. So instead, what I do
2032: # is either have or don't have an "onclick" handler that
2033: # does nothing, give Published files the onclick handler, and
2034: # have the checker scripts check for that. Stupid and clumsy,
2035: # and only gives us binary "yes/no" information (at least I
2036: # couldn't figure out how to reach into the event handler's
2037: # actual code to retreive a value), but it works well enough
2038: # here.
1.23 bowersj2 2039:
1.22 bowersj2 2040: my $onclick = '';
1.23 bowersj2 2041: if ($status eq 'Published' && $helper->{VARS}->{'construction'}) {
1.22 bowersj2 2042: $onclick = 'onclick="a=1" ';
2043: }
1.20 bowersj2 2044: $result .= '<tr><td align="right"' . " bgcolor='$color'>" .
1.22 bowersj2 2045: "<input $onclick type='$type' name='" . $var
1.5 bowersj2 2046: . ".forminput' value='" . HTML::Entities::encode($fileName) .
2047: "'";
2048: if (!$self->{'multichoice'} && $choices == 0) {
2049: $result .= ' checked';
2050: }
1.20 bowersj2 2051: $result .= "/></td><td bgcolor='$color'>" . $file .
2052: "</td><td bgcolor='$color'>$status</td></tr>\n";
1.5 bowersj2 2053: $choices++;
2054: }
2055: }
2056:
2057: $result .= "</table>\n";
2058:
2059: if (!$choices) {
2060: $result .= '<font color="#FF0000">There are no files available to select in this directory. Please go back and select another option.</font><br /><br />';
2061: }
2062:
2063: $result .= $buttons;
2064:
2065: return $result;
1.20 bowersj2 2066: }
2067:
2068: # Determine the state of the file: Published, unpublished, modified.
2069: # Return the color it should be in and a label as a two-element array
2070: # reference.
2071: # Logic lifted from lonpubdir.pm, even though I don't know that it's still
2072: # the most right thing to do.
2073:
2074: sub fileState {
2075: my $constructionSpaceDir = shift;
2076: my $file = shift;
2077:
2078: my $docroot = $Apache::lonnet::perlvar{'lonDocRoot'};
2079: my $subdirpart = $constructionSpaceDir;
2080: $subdirpart =~ s/^\/home\/$ENV{'user.name'}\/public_html//;
2081: my $resdir = $docroot . '/res/' . $ENV{'user.domain'} . '/' . $ENV{'user.name'} .
2082: $subdirpart;
2083:
2084: my @constructionSpaceFileStat = stat($constructionSpaceDir . '/' . $file);
2085: my @resourceSpaceFileStat = stat($resdir . '/' . $file);
2086: if (!@resourceSpaceFileStat) {
2087: return ['Unpublished', '#FFCCCC'];
2088: }
2089:
2090: my $constructionSpaceFileModified = $constructionSpaceFileStat[9];
2091: my $resourceSpaceFileModified = $resourceSpaceFileStat[9];
2092:
2093: if ($constructionSpaceFileModified > $resourceSpaceFileModified) {
2094: return ['Modified', '#FFFFCC'];
2095: }
2096: return ['Published', '#CCFFCC'];
1.4 bowersj2 2097: }
1.5 bowersj2 2098:
1.4 bowersj2 2099: sub postprocess {
2100: my $self = shift;
1.6 bowersj2 2101: my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
2102: if (!$result) {
2103: $self->{ERROR_MSG} = 'You must choose at least one file '.
2104: 'to continue.';
2105: return 0;
2106: }
2107:
1.5 bowersj2 2108: if (defined($self->{NEXTSTATE})) {
2109: $helper->changeState($self->{NEXTSTATE});
1.3 bowersj2 2110: }
1.6 bowersj2 2111:
2112: return 1;
1.3 bowersj2 2113: }
1.8 bowersj2 2114:
2115: 1;
2116:
1.11 bowersj2 2117: package Apache::lonhelper::section;
2118:
2119: =pod
2120:
2121: =head2 Element: section
2122:
2123: <section> allows the user to choose one or more sections from the current
2124: course.
2125:
2126: It takes the standard attributes "variable", "multichoice", and
2127: "nextstate", meaning what they do for most other elements.
2128:
2129: =cut
2130:
2131: no strict;
2132: @ISA = ("Apache::lonhelper::choices");
2133: use strict;
2134:
2135: BEGIN {
2136: &Apache::lonhelper::register('Apache::lonhelper::section',
2137: ('section'));
2138: }
2139:
2140: sub new {
2141: my $ref = Apache::lonhelper::choices->new();
2142: bless($ref);
2143: }
2144:
2145: sub start_section {
2146: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2147:
2148: if ($target ne 'helper') {
2149: return '';
2150: }
1.12 bowersj2 2151:
2152: $paramHash->{CHOICES} = [];
2153:
1.11 bowersj2 2154: $paramHash->{'variable'} = $token->[2]{'variable'};
2155: $helper->declareVar($paramHash->{'variable'});
2156: $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
2157: if (defined($token->[2]{'nextstate'})) {
1.12 bowersj2 2158: $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
1.11 bowersj2 2159: }
2160:
2161: # Populate the CHOICES element
2162: my %choices;
2163:
2164: my $section = Apache::loncoursedata::CL_SECTION();
2165: my $classlist = Apache::loncoursedata::get_classlist();
2166: foreach (keys %$classlist) {
2167: my $sectionName = $classlist->{$_}->[$section];
2168: if (!$sectionName) {
2169: $choices{"No section assigned"} = "";
2170: } else {
2171: $choices{$sectionName} = $sectionName;
2172: }
1.12 bowersj2 2173: }
2174:
1.11 bowersj2 2175: for my $sectionName (sort(keys(%choices))) {
1.12 bowersj2 2176:
1.11 bowersj2 2177: push @{$paramHash->{CHOICES}}, [$sectionName, $sectionName];
2178: }
2179: }
2180:
1.12 bowersj2 2181: sub end_section {
2182: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.11 bowersj2 2183:
1.12 bowersj2 2184: if ($target ne 'helper') {
2185: return '';
2186: }
2187: Apache::lonhelper::section->new();
2188: }
1.11 bowersj2 2189: 1;
2190:
1.8 bowersj2 2191: package Apache::lonhelper::general;
2192:
2193: =pod
2194:
2195: =head2 General-purpose tag: <exec>
2196:
2197: The contents of the exec tag are executed as Perl code, not inside a
2198: safe space, so the full range of $ENV and such is available. The code
2199: will be executed as a subroutine wrapped with the following code:
2200:
2201: "sub { my $helper = shift; my $state = shift;" and
2202:
2203: "}"
2204:
2205: The return value is ignored.
2206:
2207: $helper is the helper object. Feel free to add methods to the helper
2208: object to support whatever manipulation you may need to do (for instance,
2209: overriding the form location if the state is the final state; see
2210: lonparm.helper for an example).
2211:
2212: $state is the $paramHash that has currently been generated and may
2213: be manipulated by the code in exec. Note that the $state is not yet
2214: an actual state B<object>, it is just a hash, so do not expect to
2215: be able to call methods on it.
2216:
2217: =cut
2218:
2219: BEGIN {
2220: &Apache::lonhelper::register('Apache::lonhelper::general',
1.11 bowersj2 2221: 'exec', 'condition', 'clause',
2222: 'eval');
1.8 bowersj2 2223: }
2224:
2225: sub start_exec {
2226: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2227:
2228: if ($target ne 'helper') {
2229: return '';
2230: }
2231:
2232: my $code = &Apache::lonxml::get_all_text('/exec', $parser);
2233:
2234: $code = eval ('sub { my $helper = shift; my $state = shift; ' .
2235: $code . "}");
1.11 bowersj2 2236: die 'Error in <exec>, Perl said: '. $@ if $@;
1.8 bowersj2 2237: &$code($helper, $paramHash);
2238: }
2239:
2240: sub end_exec { return ''; }
2241:
2242: =pod
2243:
2244: =head2 General-purpose tag: <condition>
2245:
2246: The <condition> tag allows you to mask out parts of the helper code
2247: depending on some programatically determined condition. The condition
2248: tag contains a tag <clause> which contains perl code that when wrapped
2249: with "sub { my $helper = shift; my $state = shift; " and "}", returns
2250: a true value if the XML in the condition should be evaluated as a normal
2251: part of the helper, or false if it should be completely discarded.
2252:
2253: The <clause> tag must be the first sub-tag of the <condition> tag or
2254: it will not work as expected.
2255:
2256: =cut
2257:
2258: # The condition tag just functions as a marker, it doesn't have
2259: # to "do" anything. Technically it doesn't even have to be registered
2260: # with the lonxml code, but I leave this here to be explicit about it.
2261: sub start_condition { return ''; }
2262: sub end_condition { return ''; }
2263:
2264: sub start_clause {
2265: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2266:
2267: if ($target ne 'helper') {
2268: return '';
2269: }
2270:
2271: my $clause = Apache::lonxml::get_all_text('/clause', $parser);
2272: $clause = eval('sub { my $helper = shift; my $state = shift; '
2273: . $clause . '}');
1.11 bowersj2 2274: die 'Error in clause of condition, Perl said: ' . $@ if $@;
1.8 bowersj2 2275: if (!&$clause($helper, $paramHash)) {
2276: # Discard all text until the /condition.
2277: &Apache::lonxml::get_all_text('/condition', $parser);
2278: }
2279: }
2280:
2281: sub end_clause { return ''; }
1.11 bowersj2 2282:
2283: =pod
2284:
2285: =head2 General-purpose tag: <eval>
2286:
2287: The <eval> tag will be evaluated as a subroutine call passed in the
2288: current helper object and state hash as described in <condition> above,
2289: but is expected to return a string to be printed directly to the
2290: screen. This is useful for dynamically generating messages.
2291:
2292: =cut
2293:
2294: # This is basically a type of message.
2295: # Programmatically setting $paramHash->{NEXTSTATE} would work, though
2296: # it's probably bad form.
2297:
2298: sub start_eval {
2299: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2300:
2301: if ($target ne 'helper') {
2302: return '';
2303: }
2304:
2305: my $program = Apache::lonxml::get_all_text('/eval', $parser);
2306: $program = eval('sub { my $helper = shift; my $state = shift; '
2307: . $program . '}');
2308: die 'Error in eval code, Perl said: ' . $@ if $@;
2309: $paramHash->{MESSAGE_TEXT} = &$program($helper, $paramHash);
2310: }
2311:
2312: sub end_eval {
2313: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2314:
2315: if ($target ne 'helper') {
2316: return '';
2317: }
2318:
2319: Apache::lonhelper::message->new();
2320: }
2321:
1.13 bowersj2 2322: 1;
2323:
1.27 bowersj2 2324: package Apache::lonhelper::final;
2325:
2326: =pod
2327:
2328: =head2 Element: final
2329:
2330: <final> is a special element that works with helpers that use the <finalcode>
2331: tag. It goes through all the states and elements, executing the <finalcode>
2332: snippets and collecting the results. Finally, it takes the user out of the
2333: helper, going to a provided page.
2334:
2335: =cut
2336:
2337: no strict;
2338: @ISA = ("Apache::lonhelper::element");
2339: use strict;
2340:
2341: BEGIN {
2342: &Apache::lonhelper::register('Apache::lonhelper::final',
2343: ('final', 'exitpage'));
2344: }
2345:
2346: sub new {
2347: my $ref = Apache::lonhelper::element->new();
2348: bless($ref);
2349: }
2350:
2351: sub start_final { return ''; }
2352:
2353: sub end_final {
2354: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2355:
2356: if ($target ne 'helper') {
2357: return '';
2358: }
2359:
2360: Apache::lonhelper::final->new();
2361:
2362: return '';
2363: }
2364:
2365: sub start_exitpage {
2366: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2367:
2368: if ($target ne 'helper') {
2369: return '';
2370: }
2371:
2372: $paramHash->{EXIT_PAGE} = &Apache::lonxml::get_all_text('/exitpage',
2373: $parser);
2374:
2375: return '';
2376: }
2377:
2378: sub end_exitpage { return ''; }
2379:
2380: sub render {
2381: my $self = shift;
2382:
2383: my @results;
2384:
2385: # Collect all the results
2386: for my $stateName (keys %{$helper->{STATES}}) {
2387: my $state = $helper->{STATES}->{$stateName};
2388:
2389: for my $element (@{$state->{ELEMENTS}}) {
2390: if (defined($element->{FINAL_CODE})) {
2391: # Compile the code.
2392: my $code = 'sub { my $helper = shift; ' . $element->{FINAL_CODE} .
2393: '}';
2394: $code = eval($code);
2395: die 'Error while executing final code for element with var ' .
2396: $element->{'variable'} . ', Perl said: ' . $@ if $@;
2397:
2398: my $result = &$code($helper);
2399: if ($result) {
2400: push @results, $result;
2401: }
2402: }
2403: }
2404: }
2405:
2406: if (scalar(@results) == 0) {
2407: return '';
2408: }
2409:
2410: my $result = "<ul>\n";
2411: for my $re (@results) {
2412: $result .= ' <li>' . $re . "</li>\n";
2413: }
2414: return $result . '</ul>';
2415: }
2416:
2417: 1;
2418:
1.13 bowersj2 2419: package Apache::lonhelper::parmwizfinal;
2420:
2421: # This is the final state for the parmwizard. It is not generally useful,
2422: # so it is not perldoc'ed. It does its own processing.
2423: # It is represented with <parmwizfinal />, and
2424: # should later be moved to lonparmset.pm .
2425:
2426: no strict;
2427: @ISA = ('Apache::lonhelper::element');
2428: use strict;
1.11 bowersj2 2429:
1.13 bowersj2 2430: BEGIN {
2431: &Apache::lonhelper::register('Apache::lonhelper::parmwizfinal',
2432: ('parmwizfinal'));
2433: }
2434:
2435: use Time::localtime;
2436:
2437: sub new {
2438: my $ref = Apache::lonhelper::choices->new();
2439: bless ($ref);
2440: }
2441:
2442: sub start_parmwizfinal { return ''; }
2443:
2444: sub end_parmwizfinal {
2445: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
2446:
2447: if ($target ne 'helper') {
2448: return '';
2449: }
2450: Apache::lonhelper::parmwizfinal->new();
2451: }
2452:
2453: # Renders a form that, when submitted, will form the input to lonparmset.pm
2454: sub render {
2455: my $self = shift;
2456: my $vars = $helper->{VARS};
2457:
2458: # FIXME: Unify my designators with the standard ones
2459: my %dateTypeHash = ('open_date' => "Opening Date",
2460: 'due_date' => "Due Date",
2461: 'answer_date' => "Answer Date");
2462: my %parmTypeHash = ('open_date' => "0_opendate",
2463: 'due_date' => "0_duedate",
2464: 'answer_date' => "0_answerdate");
2465:
2466: my $affectedResourceId = "";
2467: my $parm_name = $parmTypeHash{$vars->{ACTION_TYPE}};
2468: my $level = "";
1.27 bowersj2 2469: my $resourceString;
2470: my $symb;
2471: my $paramlevel;
2472:
1.13 bowersj2 2473: # Print the granularity, depending on the action
2474: if ($vars->{GRANULARITY} eq 'whole_course') {
1.27 bowersj2 2475: $resourceString .= '<li>for <b>all resources in the course</b></li>';
1.13 bowersj2 2476: $level = 9; # general course, see lonparmset.pm perldoc
2477: $affectedResourceId = "0.0";
1.27 bowersj2 2478: $symb = 'a';
2479: $paramlevel = 'general';
1.13 bowersj2 2480: } elsif ($vars->{GRANULARITY} eq 'map') {
2481: my $navmap = Apache::lonnavmaps::navmap->new(
2482: $ENV{"request.course.fn"}.".db",
2483: $ENV{"request.course.fn"}."_parms.db", 0, 0);
2484: my $res = $navmap->getById($vars->{RESOURCE_ID});
2485: my $title = $res->compTitle();
1.27 bowersj2 2486: $symb = $res->symb();
1.13 bowersj2 2487: $navmap->untieHashes();
1.27 bowersj2 2488: $resourceString .= "<li>for the map named <b>$title</b></li>";
1.13 bowersj2 2489: $level = 8;
2490: $affectedResourceId = $vars->{RESOURCE_ID};
1.27 bowersj2 2491: $paramlevel = 'map';
1.13 bowersj2 2492: } else {
2493: my $navmap = Apache::lonnavmaps::navmap->new(
2494: $ENV{"request.course.fn"}.".db",
2495: $ENV{"request.course.fn"}."_parms.db", 0, 0);
2496: my $res = $navmap->getById($vars->{RESOURCE_ID});
1.27 bowersj2 2497: $symb = $res->symb();
1.13 bowersj2 2498: my $title = $res->compTitle();
2499: $navmap->untieHashes();
1.27 bowersj2 2500: $resourceString .= "<li>for the resource named <b>$title</b></li>";
1.13 bowersj2 2501: $level = 7;
2502: $affectedResourceId = $vars->{RESOURCE_ID};
1.27 bowersj2 2503: $paramlevel = 'full';
1.13 bowersj2 2504: }
2505:
1.27 bowersj2 2506: my $result = "<form name='helpform' method='get' action='/adm/parmset#$affectedResourceId&$parm_name&$level'>\n";
2507: $result .= '<p>Confirm that this information is correct, then click "Finish Wizard" to complete setting the parameter.<ul>';
2508:
2509: # Print the type of manipulation:
2510: $result .= '<li>Setting the <b>' . $dateTypeHash{$vars->{ACTION_TYPE}}
2511: . "</b></li>\n";
2512: if ($vars->{ACTION_TYPE} eq 'due_date' ||
2513: $vars->{ACTION_TYPE} eq 'answer_date') {
2514: # for due dates, we default to "date end" type entries
2515: $result .= "<input type='hidden' name='recent_date_end' " .
2516: "value='" . $vars->{PARM_DATE} . "' />\n";
2517: $result .= "<input type='hidden' name='pres_value' " .
2518: "value='" . $vars->{PARM_DATE} . "' />\n";
2519: $result .= "<input type='hidden' name='pres_type' " .
2520: "value='date_end' />\n";
2521: } elsif ($vars->{ACTION_TYPE} eq 'open_date') {
2522: $result .= "<input type='hidden' name='recent_date_start' ".
2523: "value='" . $vars->{PARM_DATE} . "' />\n";
2524: $result .= "<input type='hidden' name='pres_value' " .
2525: "value='" . $vars->{PARM_DATE} . "' />\n";
2526: $result .= "<input type='hidden' name='pres_type' " .
2527: "value='date_start' />\n";
2528: }
2529:
2530: $result .= $resourceString;
2531:
1.13 bowersj2 2532: # Print targets
2533: if ($vars->{TARGETS} eq 'course') {
2534: $result .= '<li>for <b>all students in course</b></li>';
2535: } elsif ($vars->{TARGETS} eq 'section') {
2536: my $section = $vars->{SECTION_NAME};
2537: $result .= "<li>for section <b>$section</b></li>";
2538: $level -= 3;
2539: $result .= "<input type='hidden' name='csec' value='" .
2540: HTML::Entities::encode($section) . "' />\n";
2541: } else {
2542: # FIXME: This is probably wasteful! Store the name!
2543: my $classlist = Apache::loncoursedata::get_classlist();
1.27 bowersj2 2544: my $username = $vars->{USER_NAME};
2545: # Chop off everything after the last colon (section)
2546: $username = substr($username, 0, rindex($username, ':'));
2547: my $name = $classlist->{$username}->[6];
1.13 bowersj2 2548: $result .= "<li>for <b>$name</b></li>";
2549: $level -= 6;
2550: my ($uname, $udom) = split /:/, $vars->{USER_NAME};
2551: $result .= "<input type='hidden' name='uname' value='".
2552: HTML::Entities::encode($uname) . "' />\n";
2553: $result .= "<input type='hidden' name='udom' value='".
2554: HTML::Entities::encode($udom) . "' />\n";
2555: }
2556:
2557: # Print value
2558: $result .= "<li>to <b>" . ctime($vars->{PARM_DATE}) . "</b> (" .
2559: Apache::lonnavmaps::timeToHumanString($vars->{PARM_DATE})
2560: . ")</li>\n";
2561:
2562: # print pres_marker
2563: $result .= "\n<input type='hidden' name='pres_marker'" .
2564: " value='$affectedResourceId&$parm_name&$level' />\n";
1.27 bowersj2 2565:
2566: # Make the table appear
2567: $result .= "\n<input type='hidden' value='true' name='prevvisit' />";
2568: $result .= "\n<input type='hidden' value='all' name='pschp' />";
2569: $result .= "\n<input type='hidden' value='$symb' name='pssymb' />";
2570: $result .= "\n<input type='hidden' value='$paramlevel' name='parmlev' />";
1.13 bowersj2 2571:
2572: $result .= "<br /><br /><center><input type='submit' value='Finish Helper' /></center></form>\n";
2573:
2574: return $result;
2575: }
2576:
2577: sub overrideForm {
2578: return 1;
2579: }
1.5 bowersj2 2580:
1.4 bowersj2 2581: 1;
1.3 bowersj2 2582:
1.1 bowersj2 2583: __END__
1.3 bowersj2 2584:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>