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