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