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