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