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