File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.13: download - view: text, annotated - select for diffs
Wed Apr 30 15:18:36 2003 UTC (21 years, 2 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Make it possible to create helpers manually, by exposing the functionality
necessary to do that.

    1: # The LearningOnline Network with CAPA
    2: # .helper XML handler to implement the LON-CAPA helper
    3: #
    4: # $Id: lonhelper.pm,v 1.13 2003/04/30 15:18:36 bowersj2 Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # (Page Handler
   29: #
   30: # (.helper handler
   31: #
   32: 
   33: =pod
   34: 
   35: =head1 lonhelper - HTML Helper framework for LON-CAPA
   36: 
   37: Helpers, often known as "wizards", are well-established UI widgets that users
   38: feel comfortable with. It can take a complicated multidimensional problem the
   39: user has and turn it into a series of bite-sized one-dimensional questions.
   40: 
   41: For developers, helpers provide an easy way to bundle little bits of functionality
   42: for the user, without having to write the tedious state-maintenence code.
   43: 
   44: Helpers are defined as XML documents, placed in the /home/httpd/html/adm/helpers 
   45: directory and having the .helper file extension. For examples, see that directory.
   46: 
   47: All classes are in the Apache::lonhelper namespace.
   48: 
   49: =head2 lonhelper XML file format
   50: 
   51: A helper consists of a top-level <helper> tag which contains a series of states.
   52: Each state contains one or more state elements, which are what the user sees, like
   53: messages, resource selections, or date queries.
   54: 
   55: The helper tag is required to have one attribute, "title", which is the name
   56: of the helper itself, such as "Parameter helper". 
   57: 
   58: =head2 State tags
   59: 
   60: State tags are required to have an attribute "name", which is the symbolic
   61: name of the state and will not be directly seen by the user. The helper is
   62: required to have one state named "START", which is the state the helper
   63: will start with. By convention, this state should clearly describe what
   64: the helper will do for the user, and may also include the first information
   65: entry the user needs to do for the helper.
   66: 
   67: State tags are also required to have an attribute "title", which is the
   68: human name of the state, and will be displayed as the header on top of 
   69: the screen for the user.
   70: 
   71: =head2 Example Helper Skeleton
   72: 
   73: An example of the tags so far:
   74: 
   75:  <helper title="Example Helper">
   76:    <state name="START" title="Demonstrating the Example Helper">
   77:      <!-- notice this is the START state the wizard requires -->
   78:      </state>
   79:    <state name="GET_NAME" title="Enter Student Name">
   80:      </state>
   81:    </helper>
   82: 
   83: Of course this does nothing. In order for the wizard to do something, it is
   84: necessary to put actual elements into the wizard. Documentation for each
   85: of these elements follows.
   86: 
   87: =head2 Creating a Helper With Code, Not XML
   88: 
   89: In some situations, such as the printing wizard (see lonprintout.pm), 
   90: writing the helper in XML would be too complicated, because of scope 
   91: issues or the fact that the code actually outweighs the XML. It is
   92: possible to create a helper via code, though it is a little odd.
   93: 
   94: Creating a helper via code is more like issuing commands to create
   95: a helper then normal code writing. For instance, elements will automatically
   96: be added to the last state created, so it's important to create the 
   97: states in the correct order.
   98: 
   99: First, create a new helper:
  100: 
  101:  use Apache::lonhelper;
  102: 
  103:  my $helper = Apache::lonhelper::new->("Helper Title");
  104: 
  105: Next you'll need to manually add states to the helper:
  106: 
  107:  Apache::lonhelper::state->new("STATE_NAME", "State's Human Title");
  108: 
  109: You don't need to save a reference to it because all elements up until
  110: the next state creation will automatically be added to this state.
  111: 
  112: Elements are created by populating the $paramHash in 
  113: Apache::lonhelper::paramhash. To prevent namespace issues, retrieve 
  114: a reference to that has with getParamHash:
  115: 
  116:  my $paramHash = Apache::lonhelper::getParamHash();
  117: 
  118: You will need to do this for each state you create.
  119: 
  120: Populate the $paramHash with the parameters for the element you wish
  121: to add next; the easiest way to find out what those entries are is
  122: to read the code. Some common ones are 'variable' to record the variable
  123: to store the results in, and NEXTSTATE to record a next state transition.
  124: 
  125: Then create your element:
  126: 
  127:  $paramHash->{MESSAGETEXT} = "This is a message.";
  128:  Apache::lonhelper::message->new();
  129: 
  130: The creation will take the $paramHash and bless it into a
  131: Apache::lonhelper::message object. To create the next element, you need
  132: to get a reference to the new, empty $paramHash:
  133: 
  134:  $paramHash = Apache::lonhelper::getParamHash();
  135: 
  136: and you can repeat creating elements that way. You can add states
  137: and elements as needed.
  138: 
  139: See lonprintout.pm, subroutine printHelper for an example of this, where
  140: we dynamically add some states to prevent security problems, for instance.
  141: 
  142: Normally the machinery in the XML format is sufficient; dynamically 
  143: adding states can easily be done by wrapping the state in a <condition>
  144: tag. This should only be used when the code dominates the XML content,
  145: the code is so complicated that it is difficult to get access to
  146: all of the information you need because of scoping issues, or so much
  147: of the information used is persistent because would-be <exec> or 
  148: <eval> blocks that using the {DATA} mechanism results in hard-to-read
  149: and -maintain code.
  150: 
  151: It is possible to do some of the work with an XML fragment parsed by
  152: lonxml; again, see lonprintout.pm for an example.
  153: 
  154: =cut
  155: 
  156: package Apache::lonhelper;
  157: use Apache::Constants qw(:common);
  158: use Apache::File;
  159: use Apache::lonxml;
  160: 
  161: # Register all the tags with the helper, so the helper can 
  162: # push and pop them
  163: 
  164: my @helperTags;
  165: 
  166: sub register {
  167:     my ($namespace, @tags) = @_;
  168: 
  169:     for my $tag (@tags) {
  170:         push @helperTags, [$namespace, $tag];
  171:     }
  172: }
  173: 
  174: BEGIN {
  175:     Apache::lonxml::register('Apache::lonhelper', 
  176:                              ('helper'));
  177:       register('Apache::lonhelper', ('state'));
  178: }
  179: 
  180: # Since all helpers are only three levels deep (helper tag, state tag, 
  181: # substate type), it's easier and more readble to explicitly track 
  182: # those three things directly, rather then futz with the tag stack 
  183: # every time.
  184: my $helper;
  185: my $state;
  186: my $substate;
  187: # To collect parameters, the contents of the subtags are collected
  188: # into this paramHash, then passed to the element object when the 
  189: # end of the element tag is located.
  190: my $paramHash; 
  191: 
  192: # For debugging purposes, one can send a second parameter into this
  193: # function, the 'uri' of the helper you wish to have rendered, and
  194: # call this from other handlers.
  195: sub handler {
  196:     my $r = shift;
  197:     my $uri = shift;
  198:     if (!defined($uri)) { $uri = $r->uri(); }
  199:     $ENV{'request.uri'} = $uri;
  200:     my $filename = '/home/httpd/html' . $uri;
  201:     my $fh = Apache::File->new($filename);
  202:     my $file;
  203:     read $fh, $file, 100000000;
  204: 
  205:     Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
  206: 
  207:     # Send header, don't cache this page
  208:     if ($r->header_only) {
  209:         if ($ENV{'browser.mathml'}) {
  210:             $r->content_type('text/xml');
  211:         } else {
  212:             $r->content_type('text/html');
  213:         }
  214:         $r->send_http_header;
  215:         return OK;
  216:     }
  217:     if ($ENV{'browser.mathml'}) {
  218:         $r->content_type('text/xml');
  219:     } else {
  220:         $r->content_type('text/html');
  221:     }
  222:     $r->send_http_header;
  223:     $r->rflush();
  224: 
  225:     # Discard result, we just want the objects that get created by the
  226:     # xml parsing
  227:     &Apache::lonxml::xmlparse($r, 'helper', $file);
  228: 
  229:     $helper->process();
  230: 
  231:     $r->print($helper->display());
  232:    return OK;
  233: }
  234: 
  235: sub registerHelperTags {
  236:     for my $tagList (@helperTags) {
  237:         Apache::lonxml::register($tagList->[0], $tagList->[1]);
  238:     }
  239: }
  240: 
  241: sub unregisterHelperTags {
  242:     for my $tagList (@helperTags) {
  243:         Apache::lonxml::deregister($tagList->[0], $tagList->[1]);
  244:     }
  245: }
  246: 
  247: sub start_helper {
  248:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  249: 
  250:     if ($target ne 'helper') {
  251:         return '';
  252:     }
  253: 
  254:     registerHelperTags();
  255: 
  256:     Apache::lonhelper::helper->new($token->[2]{'title'});
  257:     return '';
  258: }
  259: 
  260: sub end_helper {
  261:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  262:     
  263:     if ($target ne 'helper') {
  264:         return '';
  265:     }
  266: 
  267:     unregisterHelperTags();
  268: 
  269:     return '';
  270: }
  271: 
  272: sub start_state {
  273:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  274: 
  275:     if ($target ne 'helper') {
  276:         return '';
  277:     }
  278: 
  279:     Apache::lonhelper::state->new($token->[2]{'name'},
  280:                                   $token->[2]{'title'});
  281:     return '';
  282: }
  283: 
  284: # Use this to get the param hash from other files.
  285: sub getParamHash {
  286:     return $paramHash;
  287: }
  288: 
  289: # Use this to get the helper, if implementing elements in other files
  290: # (like lonprintout.pm)
  291: sub getHelper {
  292:     return $helper;
  293: }
  294: 
  295: # don't need this, so ignore it
  296: sub end_state {
  297:     return '';
  298: }
  299: 
  300: 1;
  301: 
  302: package Apache::lonhelper::helper;
  303: 
  304: use Digest::MD5 qw(md5_hex);
  305: use HTML::Entities;
  306: use Apache::loncommon;
  307: use Apache::File;
  308: 
  309: sub new {
  310:     my $proto = shift;
  311:     my $class = ref($proto) || $proto;
  312:     my $self = {};
  313: 
  314:     $self->{TITLE} = shift;
  315:     
  316:     # If there is a state from the previous form, use that. If there is no
  317:     # state, use the start state parameter.
  318:     if (defined $ENV{"form.CURRENT_STATE"})
  319:     {
  320: 	$self->{STATE} = $ENV{"form.CURRENT_STATE"};
  321:     }
  322:     else
  323:     {
  324: 	$self->{STATE} = "START";
  325:     }
  326: 
  327:     $self->{TOKEN} = $ENV{'form.TOKEN'};
  328:     # If a token was passed, we load that in. Otherwise, we need to create a 
  329:     # new storage file
  330:     # Tried to use standard Tie'd hashes, but you can't seem to take a 
  331:     # reference to a tied hash and write to it. I'd call that a wart.
  332:     if ($self->{TOKEN}) {
  333:         # Validate the token before trusting it
  334:         if ($self->{TOKEN} !~ /^[a-f0-9]{32}$/) {
  335:             # Not legit. Return nothing and let all hell break loose.
  336:             # User shouldn't be doing that!
  337:             return undef;
  338:         }
  339: 
  340:         # Get the hash.
  341:         $self->{FILENAME} = $Apache::lonnet::tmpdir . md5_hex($self->{TOKEN}); # Note the token is not the literal file
  342:         
  343:         my $file = Apache::File->new($self->{FILENAME});
  344:         my $contents = <$file>;
  345: 
  346:         # Now load in the contents
  347:         for my $value (split (/&/, $contents)) {
  348:             my ($name, $value) = split(/=/, $value);
  349:             $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  350:             $self->{VARS}->{$name} = $value;
  351:         }
  352: 
  353:         $file->close();
  354:     } else {
  355:         # Only valid if we're just starting.
  356:         if ($self->{STATE} ne 'START') {
  357:             return undef;
  358:         }
  359:         # Must create the storage
  360:         $self->{TOKEN} = md5_hex($ENV{'user.name'} . $ENV{'user.domain'} .
  361:                                  time() . rand());
  362:         $self->{FILENAME} = $Apache::lonnet::tmpdir . md5_hex($self->{TOKEN});
  363:     }
  364: 
  365:     # OK, we now have our persistent storage.
  366: 
  367:     if (defined $ENV{"form.RETURN_PAGE"})
  368:     {
  369: 	$self->{RETURN_PAGE} = $ENV{"form.RETURN_PAGE"};
  370:     }
  371:     else
  372:     {
  373: 	$self->{RETURN_PAGE} = $ENV{REFERER};
  374:     }
  375: 
  376:     $self->{STATES} = {};
  377:     $self->{DONE} = 0;
  378: 
  379:     # Used by various helpers for various things; see lonparm.helper
  380:     # for an example.
  381:     $self->{DATA} = {};
  382: 
  383:     $helper = $self;
  384: 
  385:     # Establish the $paramHash
  386:     $paramHash = {};
  387: 
  388:     bless($self, $class);
  389:     return $self;
  390: }
  391: 
  392: # Private function; returns a string to construct the hidden fields
  393: # necessary to have the helper track state.
  394: sub _saveVars {
  395:     my $self = shift;
  396:     my $result = "";
  397:     $result .= '<input type="hidden" name="CURRENT_STATE" value="' .
  398:         HTML::Entities::encode($self->{STATE}) . "\" />\n";
  399:     $result .= '<input type="hidden" name="TOKEN" value="' .
  400:         $self->{TOKEN} . "\" />\n";
  401:     $result .= '<input type="hidden" name="RETURN_PAGE" value="' .
  402:         HTML::Entities::encode($self->{RETURN_PAGE}) . "\" />\n";
  403: 
  404:     return $result;
  405: }
  406: 
  407: # Private function: Create the querystring-like representation of the stored
  408: # data to write to disk.
  409: sub _varsInFile {
  410:     my $self = shift;
  411:     my @vars = ();
  412:     for my $key (keys %{$self->{VARS}}) {
  413:         push @vars, &Apache::lonnet::escape($key) . '=' .
  414:             &Apache::lonnet::escape($self->{VARS}->{$key});
  415:     }
  416:     return join ('&', @vars);
  417: }
  418: 
  419: # Use this to declare variables.
  420: # FIXME: Document this
  421: sub declareVar {
  422:     my $self = shift;
  423:     my $var = shift;
  424: 
  425:     if (!defined($self->{VARS}->{$var})) {
  426:         $self->{VARS}->{$var} = '';
  427:     }
  428: 
  429:     my $envname = 'form.' . $var . '.forminput';
  430:     if (defined($ENV{$envname})) {
  431:         $self->{VARS}->{$var} = $ENV{$envname};
  432:     }
  433: }
  434: 
  435: sub changeState {
  436:     my $self = shift;
  437:     $self->{STATE} = shift;
  438: }
  439: 
  440: sub registerState {
  441:     my $self = shift;
  442:     my $state = shift;
  443: 
  444:     my $stateName = $state->name();
  445:     $self->{STATES}{$stateName} = $state;
  446: }
  447: 
  448: sub process {
  449:     my $self = shift;
  450: 
  451:     # Phase 1: Post processing for state of previous screen (which is actually
  452:     # the "current state" in terms of the helper variables), if it wasn't the 
  453:     # beginning state.
  454:     if ($self->{STATE} ne "START" || $ENV{"form.SUBMIT"} eq "Next ->") {
  455: 	my $prevState = $self->{STATES}{$self->{STATE}};
  456:         $prevState->postprocess();
  457:     }
  458:     
  459:     # Note, to handle errors in a state's input that a user must correct,
  460:     # do not transition in the postprocess, and force the user to correct
  461:     # the error.
  462: 
  463:     # Phase 2: Preprocess current state
  464:     my $startState = $self->{STATE};
  465:     my $state = $self->{STATES}{$startState};
  466:     
  467:     # For debugging, print something here to determine if you're going
  468:     # to an undefined state.
  469:     if (!defined($state)) {
  470:         return;
  471:     }
  472:     $state->preprocess();
  473: 
  474:     # Phase 3: While the current state is different from the previous state,
  475:     # keep processing.
  476:     while ( $startState ne $self->{STATE} )
  477:     {
  478: 	$startState = $self->{STATE};
  479: 	$state = $self->{STATES}{$startState};
  480: 	$state->preprocess();
  481:     }
  482: 
  483:     return;
  484: } 
  485: 
  486: # 1: Do the post processing for the previous state.
  487: # 2: Do the preprocessing for the current state.
  488: # 3: Check to see if state changed, if so, postprocess current and move to next.
  489: #    Repeat until state stays stable.
  490: # 4: Render the current state to the screen as an HTML page.
  491: sub display {
  492:     my $self = shift;
  493: 
  494:     my $state = $self->{STATES}{$self->{STATE}};
  495: 
  496:     my $result = "";
  497: 
  498:     # Phase 4: Display.
  499:     my $stateTitle = $state->title();
  500:     my $bodytag = &Apache::loncommon::bodytag("$self->{TITLE}",'','');
  501: 
  502:     $result .= <<HEADER;
  503: <html>
  504:     <head>
  505:         <title>LON-CAPA Helper: $self->{TITLE}</title>
  506:     </head>
  507:     $bodytag
  508: HEADER
  509:     if (!$state->overrideForm()) { $result.="<form name='wizform' method='GET'>"; }
  510:     $result .= <<HEADER;
  511:         <table border="0"><tr><td>
  512:         <h2><i>$stateTitle</i></h2>
  513: HEADER
  514: 
  515:     if (!$state->overrideForm()) {
  516:         $result .= $self->_saveVars();
  517:     }
  518:     $result .= $state->render() . "<p>&nbsp;</p>";
  519: 
  520:     if (!$state->overrideForm()) {
  521:         $result .= '<center>';
  522:         if ($self->{STATE} ne $self->{START_STATE}) {
  523:             #$result .= '<input name="SUBMIT" type="submit" value="&lt;- Previous" />&nbsp;&nbsp;';
  524:         }
  525:         if ($self->{DONE}) {
  526:             my $returnPage = $self->{RETURN_PAGE};
  527:             $result .= "<a href=\"$returnPage\">End Helper</a>";
  528:         }
  529:         else {
  530:             $result .= '<input name="back" type="button" ';
  531:             $result .= 'value="&lt;- Previous" onclick="history.go(-1)" /> ';
  532:             $result .= '<input name="SUBMIT" type="submit" value="Next -&gt;" />';
  533:         }
  534:         $result .= "</center>\n";
  535:     }
  536: 
  537:     #foreach my $key (keys %{$self->{VARS}}) {
  538:     #    $result .= "|$key| -> " . $self->{VARS}->{$key} . "<br />";
  539:     #}
  540: 
  541:     $result .= <<FOOTER;
  542:               </td>
  543:             </tr>
  544:           </table>
  545:         </form>
  546:     </body>
  547: </html>
  548: FOOTER
  549: 
  550:     # Handle writing out the vars to the file
  551:     my $file = Apache::File->new('>'.$self->{FILENAME});
  552:     print $file $self->_varsInFile();
  553: 
  554:     return $result;
  555: }
  556: 
  557: 1;
  558: 
  559: package Apache::lonhelper::state;
  560: 
  561: # States bundle things together and are responsible for compositing the
  562: # various elements together. It is not generally necessary for users to
  563: # use the state object directly, so it is not perldoc'ed.
  564: 
  565: # Basically, all the states do is pass calls to the elements and aggregate
  566: # the results.
  567: 
  568: sub new {
  569:     my $proto = shift;
  570:     my $class = ref($proto) || $proto;
  571:     my $self = {};
  572: 
  573:     $self->{NAME} = shift;
  574:     $self->{TITLE} = shift;
  575:     $self->{ELEMENTS} = [];
  576: 
  577:     bless($self, $class);
  578: 
  579:     $helper->registerState($self);
  580: 
  581:     $state = $self;
  582: 
  583:     return $self;
  584: }
  585: 
  586: sub name {
  587:     my $self = shift;
  588:     return $self->{NAME};
  589: }
  590: 
  591: sub title {
  592:     my $self = shift;
  593:     return $self->{TITLE};
  594: }
  595: 
  596: sub preprocess {
  597:     my $self = shift;
  598:     for my $element (@{$self->{ELEMENTS}}) {
  599:         $element->preprocess();
  600:     }
  601: }
  602: 
  603: # FIXME: Document that all postprocesses must return a true value or
  604: # the state transition will be overridden
  605: sub postprocess {
  606:     my $self = shift;
  607: 
  608:     # Save the state so we can roll it back if we need to.
  609:     my $originalState = $helper->{STATE};
  610:     my $everythingSuccessful = 1;
  611: 
  612:     for my $element (@{$self->{ELEMENTS}}) {
  613:         my $result = $element->postprocess();
  614:         if (!$result) { $everythingSuccessful = 0; }
  615:     }
  616: 
  617:     # If not all the postprocesses were successful, override
  618:     # any state transitions that may have occurred. It is the
  619:     # responsibility of the states to make sure they have 
  620:     # error handling in that case.
  621:     if (!$everythingSuccessful) {
  622:         $helper->{STATE} = $originalState;
  623:     }
  624: }
  625: 
  626: # Override the form if any element wants to.
  627: # two elements overriding the form will make a mess, but that should
  628: # be considered helper author error ;-)
  629: sub overrideForm {
  630:     my $self = shift;
  631:     for my $element (@{$self->{ELEMENTS}}) {
  632:         if ($element->overrideForm()) {
  633:             return 1;
  634:         }
  635:     }
  636:     return 0;
  637: }
  638: 
  639: sub addElement {
  640:     my $self = shift;
  641:     my $element = shift;
  642:     
  643:     push @{$self->{ELEMENTS}}, $element;
  644: }
  645: 
  646: sub render {
  647:     my $self = shift;
  648:     my @results = ();
  649: 
  650:     for my $element (@{$self->{ELEMENTS}}) {
  651:         push @results, $element->render();
  652:     }
  653:     return join("\n", @results);
  654: }
  655: 
  656: 1;
  657: 
  658: package Apache::lonhelper::element;
  659: # Support code for elements
  660: 
  661: =pod
  662: 
  663: =head2 Element Base Class
  664: 
  665: The Apache::lonhelper::element base class provides support methods for
  666: the elements to use, such as a multiple value processer.
  667: 
  668: B<Methods>:
  669: 
  670: =over 4
  671: 
  672: =item * process_multiple_choices(formName, varName): Process the form 
  673: element named "formName" and place the selected items into the helper 
  674: variable named varName. This is for things like checkboxes or 
  675: multiple-selection listboxes where the user can select more then 
  676: one entry. The selected entries are delimited by triple pipes in 
  677: the helper variables, like this:  
  678: 
  679:  CHOICE_1|||CHOICE_2|||CHOICE_3
  680: 
  681: =back
  682: 
  683: =cut
  684: 
  685: BEGIN {
  686:     &Apache::lonhelper::register('Apache::lonhelper::element',
  687:                                  ('nextstate'));
  688: }
  689: 
  690: # Because we use the param hash, this is often a sufficent
  691: # constructor
  692: sub new {
  693:     my $proto = shift;
  694:     my $class = ref($proto) || $proto;
  695:     my $self = $paramHash;
  696:     bless($self, $class);
  697: 
  698:     $self->{PARAMS} = $paramHash;
  699:     $self->{STATE} = $state;
  700:     $state->addElement($self);
  701:     
  702:     # Ensure param hash is not reused
  703:     $paramHash = {};
  704: 
  705:     return $self;
  706: }   
  707: 
  708: sub start_nextstate {
  709:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  710: 
  711:     if ($target ne 'helper') {
  712:         return '';
  713:     }
  714:     
  715:     $paramHash->{NEXTSTATE} = &Apache::lonxml::get_all_text('/nextstate',
  716:                                                              $parser);
  717:     return '';
  718: }
  719: 
  720: sub end_nextstate { return ''; }
  721: 
  722: sub preprocess {
  723:     return 1;
  724: }
  725: 
  726: sub postprocess {
  727:     return 1;
  728: }
  729: 
  730: sub render {
  731:     return '';
  732: }
  733: 
  734: sub overrideForm {
  735:     return 0;
  736: }
  737: 
  738: sub process_multiple_choices {
  739:     my $self = shift;
  740:     my $formname = shift;
  741:     my $var = shift;
  742: 
  743:     my $formvalue = $ENV{'form.' . $formname};
  744:     if ($formvalue) {
  745:         # Must extract values from querystring directly, as there
  746:         # may be more then one.
  747:         my @values;
  748:         for my $formparam (split (/&/, $ENV{QUERY_STRING})) {
  749:             my ($name, $value) = split(/=/, $formparam);
  750:             if ($name ne $formname) {
  751:                 next;
  752:             }
  753:             $value =~ tr/+/ /;
  754:             $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  755:             push @values, $value;
  756:         }
  757:         $helper->{VARS}->{$var} = join('|||', @values);
  758:     }
  759:     
  760:     return;
  761: }
  762: 
  763: 1;
  764: 
  765: package Apache::lonhelper::message;
  766: 
  767: =pod
  768: 
  769: =head2 Element: message
  770: 
  771: Message elements display the contents of their <message_text> tags, and
  772: transition directly to the state in the <nextstate> tag. Example:
  773: 
  774:  <message>
  775:    <nextstate>GET_NAME</nextstate>
  776:    <message_text>This is the <b>message</b> the user will see, 
  777:                  <i>HTML allowed</i>.</message_text>
  778:    </message>
  779: 
  780: This will display the HTML message and transition to the <nextstate> if
  781: given. The HTML will be directly inserted into the helper, so if you don't
  782: want text to run together, you'll need to manually wrap the <message_text>
  783: in <p> tags, or whatever is appropriate for your HTML.
  784: 
  785: Message tags do not add in whitespace, so if you want it, you'll need to add
  786: it into states. This is done so you can inline some elements, such as 
  787: the <date> element, right between two messages, giving the appearence that 
  788: the <date> element appears inline. (Note the elements can not be embedded
  789: within each other.)
  790: 
  791: This is also a good template for creating your own new states, as it has
  792: very little code beyond the state template.
  793: 
  794: =cut
  795: 
  796: no strict;
  797: @ISA = ("Apache::lonhelper::element");
  798: use strict;
  799: 
  800: BEGIN {
  801:     &Apache::lonhelper::register('Apache::lonhelper::message',
  802:                               ('message'));
  803: }
  804: 
  805: sub new {
  806:     my $ref = Apache::lonhelper::element->new();
  807:     bless($ref);
  808: }
  809: 
  810: # CONSTRUCTION: Construct the message element from the XML
  811: sub start_message {
  812:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  813: 
  814:     if ($target ne 'helper') {
  815:         return '';
  816:     }
  817: 
  818:     $paramHash->{MESSAGE_TEXT} = &Apache::lonxml::get_all_text('/message',
  819:                                                                $parser);
  820: 
  821:     if (defined($token->[2]{'nextstate'})) {
  822:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
  823:     }
  824:     return '';
  825: }
  826: 
  827: sub end_message {
  828:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  829: 
  830:     if ($target ne 'helper') {
  831:         return '';
  832:     }
  833:     Apache::lonhelper::message->new();
  834:     return '';
  835: }
  836: 
  837: sub render {
  838:     my $self = shift;
  839: 
  840:     return $self->{MESSAGE_TEXT};
  841: }
  842: # If a NEXTSTATE was given, switch to it
  843: sub postprocess {
  844:     my $self = shift;
  845:     if (defined($self->{NEXTSTATE})) {
  846:         $helper->changeState($self->{NEXTSTATE});
  847:     }
  848: 
  849:     return 1;
  850: }
  851: 1;
  852: 
  853: package Apache::lonhelper::choices;
  854: 
  855: =pod
  856: 
  857: =head2 Element: choices
  858: 
  859: Choice states provide a single choice to the user as a text selection box.
  860: A "choice" is two pieces of text, one which will be displayed to the user
  861: (the "human" value), and one which will be passed back to the program
  862: (the "computer" value). For instance, a human may choose from a list of
  863: resources on disk by title, while your program wants the file name.
  864: 
  865: <choices> takes an attribute "variable" to control which helper variable
  866: the result is stored in.
  867: 
  868: <choices> takes an attribute "multichoice" which, if set to a true
  869: value, will allow the user to select multiple choices.
  870: 
  871: B<SUB-TAGS>
  872: 
  873: <choices> can have the following subtags:
  874: 
  875: =over 4
  876: 
  877: =item * <nextstate>state_name</nextstate>: If given, this will cause the
  878:       choice element to transition to the given state after executing. If
  879:       this is used, do not pass nextstates to the <choice> tag.
  880: 
  881: =item * <choice />: If the choices are static,
  882:       this element will allow you to specify them. Each choice
  883:       contains  attribute, "computer", as described above. The
  884:       content of the tag will be used as the human label.
  885:       For example,  
  886:       <choice computer='234-12-7312'>Bobby McDormik</choice>.
  887: 
  888:       <choice> can take a parameter "eval", which if set to
  889:       a true value, will cause the contents of the tag to be
  890:       evaluated as it would be in an <eval> tag; see <eval> tag
  891:       below.
  892: 
  893: <choice> may optionally contain a 'nextstate' attribute, which
  894: will be the state transisitoned to if the choice is made, if
  895: the choice is not multichoice.
  896: 
  897: =back
  898: 
  899: To create the choices programmatically, either wrap the choices in 
  900: <condition> tags (prefered), or use an <exec> block inside the <choice>
  901: tag. Store the choices in $state->{CHOICES}, which is a list of list
  902: references, where each list has three strings. The first is the human
  903: name, the second is the computer name. and the third is the option
  904: next state. For example:
  905: 
  906:  <exec>
  907:     for (my $i = 65; $i < 65 + 26; $i++) {
  908:         push @{$state->{CHOICES}}, [chr($i), $i, 'next'];
  909:     }
  910:  </exec>
  911: 
  912: This will allow the user to select from the letters A-Z (in ASCII), while
  913: passing the ASCII value back into the helper variables, and the state
  914: will in all cases transition to 'next'.
  915: 
  916: You can mix and match methods of creating choices, as long as you always 
  917: "push" onto the choice list, rather then wiping it out. (You can even 
  918: remove choices programmatically, but that would probably be bad form.)
  919: 
  920: =cut
  921: 
  922: no strict;
  923: @ISA = ("Apache::lonhelper::element");
  924: use strict;
  925: 
  926: BEGIN {
  927:     &Apache::lonhelper::register('Apache::lonhelper::choices',
  928:                               ('choice', 'choices'));
  929: }
  930: 
  931: sub new {
  932:     my $ref = Apache::lonhelper::element->new();
  933:     bless($ref);
  934: }
  935: 
  936: # CONSTRUCTION: Construct the message element from the XML
  937: sub start_choices {
  938:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  939: 
  940:     if ($target ne 'helper') {
  941:         return '';
  942:     }
  943: 
  944:     # Need to initialize the choices list, so everything can assume it exists
  945:     $paramHash->{'variable'} = $token->[2]{'variable'};
  946:     $helper->declareVar($paramHash->{'variable'});
  947:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
  948:     $paramHash->{CHOICES} = [];
  949:     return '';
  950: }
  951: 
  952: sub end_choices {
  953:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  954: 
  955:     if ($target ne 'helper') {
  956:         return '';
  957:     }
  958:     Apache::lonhelper::choices->new();
  959:     return '';
  960: }
  961: 
  962: sub start_choice {
  963:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  964: 
  965:     if ($target ne 'helper') {
  966:         return '';
  967:     }
  968: 
  969:     my $computer = $token->[2]{'computer'};
  970:     my $human = &Apache::lonxml::get_all_text('/choice',
  971:                                               $parser);
  972:     my $nextstate = $token->[2]{'nextstate'};
  973:     my $evalFlag = $token->[2]{'eval'};
  974:     push @{$paramHash->{CHOICES}}, [$human, $computer, $nextstate, 
  975:                                     $evalFlag];
  976:     return '';
  977: }
  978: 
  979: sub end_choice {
  980:     return '';
  981: }
  982: 
  983: sub render {
  984:     # START HERE: Replace this with correct choices code.
  985:     my $self = shift;
  986:     my $var = $self->{'variable'};
  987:     my $buttons = '';
  988:     my $result = '';
  989: 
  990:     if ($self->{'multichoice'}) {
  991:         $result .= <<SCRIPT;
  992: <script>
  993:     function checkall(value) {
  994: 	for (i=0; i<document.forms.wizform.elements.length; i++) {
  995:             document.forms.wizform.elements[i].checked=value;
  996:         }
  997:     }
  998: </script>
  999: SCRIPT
 1000:         $buttons = <<BUTTONS;
 1001: <br />
 1002: <input type="button" onclick="checkall(true)" value="Select All" />
 1003: <input type="button" onclick="checkall(false)" value="Unselect All" />
 1004: <br />&nbsp;
 1005: BUTTONS
 1006:     }
 1007: 
 1008:     if (defined $self->{ERROR_MSG}) {
 1009:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br />';
 1010:     }
 1011: 
 1012:     $result .= $buttons;
 1013:     
 1014:     $result .= "<table>\n\n";
 1015: 
 1016:     my $type = "radio";
 1017:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
 1018:     my $checked = 0;
 1019:     foreach my $choice (@{$self->{CHOICES}}) {
 1020:         $result .= "<tr>\n<td width='20'>&nbsp;</td>\n";
 1021:         $result .= "<td valign='top'><input type='$type' name='$var.forminput'"
 1022:             . "' value='" . 
 1023:             HTML::Entities::encode($choice->[1]) 
 1024:             . "'";
 1025:         if (!$self->{'multichoice'} && !$checked) {
 1026:             $result .= " checked ";
 1027:             $checked = 1;
 1028:         }
 1029:         my $choiceLabel = $choice->[0];
 1030:         if ($choice->[4]) {  # if we need to evaluate this choice
 1031:             $choiceLabel = "sub { my $helper = shift; my $state = shift;" .
 1032:                 $choiceLabel . "}";
 1033:             $choiceLabel = eval($choiceLabel);
 1034:             $choiceLabel = &$choiceLabel($helper, $self);
 1035:         }
 1036:         $result .= "/></td><td> " . $choiceLabel . "</td></tr>\n";
 1037:     }
 1038:     $result .= "</table>\n\n\n";
 1039:     $result .= $buttons;
 1040: 
 1041:     return $result;
 1042: }
 1043: 
 1044: # If a NEXTSTATE was given or a nextstate for this choice was
 1045: # given, switch to it
 1046: sub postprocess {
 1047:     my $self = shift;
 1048:     my $chosenValue = $ENV{'form.' . $self->{'variable'} . '.forminput'};
 1049: 
 1050:     if (!$chosenValue) {
 1051:         $self->{ERROR_MSG} = "You must choose one or more choices to" .
 1052:             " continue.";
 1053:         return 0;
 1054:     }
 1055: 
 1056:     if ($self->{'multichoice'}) {
 1057:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
 1058:                                         $self->{'variable'});
 1059:     }
 1060: 
 1061:     if (defined($self->{NEXTSTATE})) {
 1062:         $helper->changeState($self->{NEXTSTATE});
 1063:     }
 1064:     
 1065:     foreach my $choice (@{$self->{CHOICES}}) {
 1066:         if ($choice->[1] eq $chosenValue) {
 1067:             if (defined($choice->[2])) {
 1068:                 $helper->changeState($choice->[2]);
 1069:             }
 1070:         }
 1071:     }
 1072:     return 1;
 1073: }
 1074: 1;
 1075: 
 1076: package Apache::lonhelper::date;
 1077: 
 1078: =pod
 1079: 
 1080: =head2 Element: date
 1081: 
 1082: Date elements allow the selection of a date with a drop down list.
 1083: 
 1084: Date elements can take two attributes:
 1085: 
 1086: =over 4
 1087: 
 1088: =item * B<variable>: The name of the variable to store the chosen
 1089:         date in. Required.
 1090: 
 1091: =item * B<hoursminutes>: If a true value, the date will show hours
 1092:         and minutes, as well as month/day/year. If false or missing,
 1093:         the date will only show the month, day, and year.
 1094: 
 1095: =back
 1096: 
 1097: Date elements contain only an option <nextstate> tag to determine
 1098: the next state.
 1099: 
 1100: Example:
 1101: 
 1102:  <date variable="DUE_DATE" hoursminutes="1">
 1103:    <nextstate>choose_why</nextstate>
 1104:    </date>
 1105: 
 1106: =cut
 1107: 
 1108: no strict;
 1109: @ISA = ("Apache::lonhelper::element");
 1110: use strict;
 1111: 
 1112: use Time::localtime;
 1113: 
 1114: BEGIN {
 1115:     &Apache::lonhelper::register('Apache::lonhelper::date',
 1116:                               ('date'));
 1117: }
 1118: 
 1119: # Don't need to override the "new" from element
 1120: sub new {
 1121:     my $ref = Apache::lonhelper::element->new();
 1122:     bless($ref);
 1123: }
 1124: 
 1125: my @months = ("January", "February", "March", "April", "May", "June", "July",
 1126: 	      "August", "September", "October", "November", "December");
 1127: 
 1128: # CONSTRUCTION: Construct the message element from the XML
 1129: sub start_date {
 1130:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1131: 
 1132:     if ($target ne 'helper') {
 1133:         return '';
 1134:     }
 1135: 
 1136:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1137:     $helper->declareVar($paramHash->{'variable'});
 1138:     $paramHash->{'hoursminutes'} = $token->[2]{'hoursminutes'};
 1139: }
 1140: 
 1141: sub end_date {
 1142:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1143: 
 1144:     if ($target ne 'helper') {
 1145:         return '';
 1146:     }
 1147:     Apache::lonhelper::date->new();
 1148:     return '';
 1149: }
 1150: 
 1151: sub render {
 1152:     my $self = shift;
 1153:     my $result = "";
 1154:     my $var = $self->{'variable'};
 1155: 
 1156:     my $date;
 1157:     
 1158:     # Default date: The current hour.
 1159:     $date = localtime();
 1160:     $date->min(0);
 1161: 
 1162:     if (defined $self->{ERROR_MSG}) {
 1163:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 1164:     }
 1165: 
 1166:     # Month
 1167:     my $i;
 1168:     $result .= "<select name='${var}month'>\n";
 1169:     for ($i = 0; $i < 12; $i++) {
 1170:         if ($i == $date->mon) {
 1171:             $result .= "<option value='$i' selected>";
 1172:         } else {
 1173:             $result .= "<option value='$i'>";
 1174:         }
 1175:         $result .= $months[$i] . "</option>\n";
 1176:     }
 1177:     $result .= "</select>\n";
 1178: 
 1179:     # Day
 1180:     $result .= "<select name='${var}day'>\n";
 1181:     for ($i = 1; $i < 32; $i++) {
 1182:         if ($i == $date->mday) {
 1183:             $result .= '<option selected>';
 1184:         } else {
 1185:             $result .= '<option>';
 1186:         }
 1187:         $result .= "$i</option>\n";
 1188:     }
 1189:     $result .= "</select>,\n";
 1190: 
 1191:     # Year
 1192:     $result .= "<select name='${var}year'>\n";
 1193:     for ($i = 2000; $i < 2030; $i++) { # update this after 64-bit dates
 1194:         if ($date->year + 1900 == $i) {
 1195:             $result .= "<option selected>";
 1196:         } else {
 1197:             $result .= "<option>";
 1198:         }
 1199:         $result .= "$i</option>\n";
 1200:     }
 1201:     $result .= "</select>,\n";
 1202: 
 1203:     # Display Hours and Minutes if they are called for
 1204:     if ($self->{'hoursminutes'}) {
 1205:         # Build hour
 1206:         $result .= "<select name='${var}hour'>\n";
 1207:         $result .= "<option " . ($date->hour == 0 ? 'selected ':'') .
 1208:             " value='0'>midnight</option>\n";
 1209:         for ($i = 1; $i < 12; $i++) {
 1210:             if ($date->hour == $i) {
 1211:                 $result .= "<option selected value='$i'>$i a.m.</option>\n";
 1212:             } else {
 1213:                 $result .= "<option value='$i'>$i a.m</option>\n";
 1214:             }
 1215:         }
 1216:         $result .= "<option " . ($date->hour == 12 ? 'selected ':'') .
 1217:             " value='12'>noon</option>\n";
 1218:         for ($i = 13; $i < 24; $i++) {
 1219:             my $printedHour = $i - 12;
 1220:             if ($date->hour == $i) {
 1221:                 $result .= "<option selected value='$i'>$printedHour p.m.</option>\n";
 1222:             } else {
 1223:                 $result .= "<option value='$i'>$printedHour p.m.</option>\n";
 1224:             }
 1225:         }
 1226: 
 1227:         $result .= "</select> :\n";
 1228: 
 1229:         $result .= "<select name='${var}minute'>\n";
 1230:         for ($i = 0; $i < 60; $i++) {
 1231:             my $printedMinute = $i;
 1232:             if ($i < 10) {
 1233:                 $printedMinute = "0" . $printedMinute;
 1234:             }
 1235:             if ($date->min == $i) {
 1236:                 $result .= "<option selected>";
 1237:             } else {
 1238:                 $result .= "<option>";
 1239:             }
 1240:             $result .= "$printedMinute</option>\n";
 1241:         }
 1242:         $result .= "</select>\n";
 1243:     }
 1244: 
 1245:     return $result;
 1246: 
 1247: }
 1248: # If a NEXTSTATE was given, switch to it
 1249: sub postprocess {
 1250:     my $self = shift;
 1251:     my $var = $self->{'variable'};
 1252:     my $month = $ENV{'form.' . $var . 'month'}; 
 1253:     my $day = $ENV{'form.' . $var . 'day'}; 
 1254:     my $year = $ENV{'form.' . $var . 'year'}; 
 1255:     my $min = 0; 
 1256:     my $hour = 0;
 1257:     if ($self->{'hoursminutes'}) {
 1258:         $min = $ENV{'form.' . $var . 'minute'};
 1259:         $hour = $ENV{'form.' . $var . 'hour'};
 1260:     }
 1261: 
 1262:     my $chosenDate = Time::Local::timelocal(0, $min, $hour, $day, $month, $year);
 1263:     # Check to make sure that the date was not automatically co-erced into a 
 1264:     # valid date, as we want to flag that as an error
 1265:     # This happens for "Feb. 31", for instance, which is coerced to March 2 or
 1266:     # 3, depending on if it's a leapyear
 1267:     my $checkDate = localtime($chosenDate);
 1268: 
 1269:     if ($checkDate->mon != $month || $checkDate->mday != $day ||
 1270:         $checkDate->year + 1900 != $year) {
 1271:         $self->{ERROR_MSG} = "Can't use " . $months[$month] . " $day, $year as a "
 1272:             . "date because it doesn't exist. Please enter a valid date.";
 1273:         return 0;
 1274:     }
 1275: 
 1276:     $helper->{VARS}->{$var} = $chosenDate;
 1277: 
 1278:     if (defined($self->{NEXTSTATE})) {
 1279:         $helper->changeState($self->{NEXTSTATE});
 1280:     }
 1281: 
 1282:     return 1;
 1283: }
 1284: 1;
 1285: 
 1286: package Apache::lonhelper::resource;
 1287: 
 1288: =pod
 1289: 
 1290: =head2 Element: resource
 1291: 
 1292: <resource> elements allow the user to select one or multiple resources
 1293: from the current course. You can filter out which resources they can view,
 1294: and filter out which resources they can select. The course will always
 1295: be displayed fully expanded, because of the difficulty of maintaining
 1296: selections across folder openings and closings. If this is fixed, then
 1297: the user can manipulate the folders.
 1298: 
 1299: <resource> takes the standard variable attribute to control what helper
 1300: variable stores the results. It also takes a "multichoice" attribute,
 1301: which controls whether the user can select more then one resource.
 1302: 
 1303: B<SUB-TAGS>
 1304: 
 1305: =over 4
 1306: 
 1307: =item * <filterfunc>: If you want to filter what resources are displayed
 1308:   to the user, use a filter func. The <filterfunc> tag should contain
 1309:   Perl code that when wrapped with "sub { my $res = shift; " and "}" is 
 1310:   a function that returns true if the resource should be displayed, 
 1311:   and false if it should be skipped. $res is a resource object. 
 1312:   (See Apache::lonnavmaps documentation for information about the 
 1313:   resource object.)
 1314: 
 1315: =item * <choicefunc>: Same as <filterfunc>, except that controls whether
 1316:   the given resource can be chosen. (It is almost always a good idea to
 1317:   show the user the folders, for instance, but you do not always want to 
 1318:   let the user select them.)
 1319: 
 1320: =item * <nextstate>: Standard nextstate behavior.
 1321: 
 1322: =item * <valuefunc>: This function controls what is returned by the resource
 1323:   when the user selects it. Like filterfunc and choicefunc, it should be
 1324:   a function fragment that when wrapped by "sub { my $res = shift; " and
 1325:   "}" returns a string representing what you want to have as the value. By
 1326:   default, the value will be the resource ID of the object ($res->{ID}).
 1327: 
 1328: =item * <mapurl>: If the URL of a map is given here, only that map
 1329:   will be displayed, instead of the whole course.
 1330: 
 1331: =back
 1332: 
 1333: =cut
 1334: 
 1335: no strict;
 1336: @ISA = ("Apache::lonhelper::element");
 1337: use strict;
 1338: 
 1339: BEGIN {
 1340:     &Apache::lonhelper::register('Apache::lonhelper::resource',
 1341:                               ('resource', 'filterfunc', 
 1342:                                'choicefunc', 'valuefunc',
 1343:                                'mapurl'));
 1344: }
 1345: 
 1346: sub new {
 1347:     my $ref = Apache::lonhelper::element->new();
 1348:     bless($ref);
 1349: }
 1350: 
 1351: # CONSTRUCTION: Construct the message element from the XML
 1352: sub start_resource {
 1353:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1354: 
 1355:     if ($target ne 'helper') {
 1356:         return '';
 1357:     }
 1358: 
 1359:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1360:     $helper->declareVar($paramHash->{'variable'});
 1361:     return '';
 1362: }
 1363: 
 1364: sub end_resource {
 1365:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1366: 
 1367:     if ($target ne 'helper') {
 1368:         return '';
 1369:     }
 1370:     if (!defined($paramHash->{FILTER_FUNC})) {
 1371:         $paramHash->{FILTER_FUNC} = sub {return 1;};
 1372:     }
 1373:     if (!defined($paramHash->{CHOICE_FUNC})) {
 1374:         $paramHash->{CHOICE_FUNC} = sub {return 1;};
 1375:     }
 1376:     if (!defined($paramHash->{VALUE_FUNC})) {
 1377:         $paramHash->{VALUE_FUNC} = sub {my $res = shift; return $res->{ID}; };
 1378:     }
 1379:     Apache::lonhelper::resource->new();
 1380:     return '';
 1381: }
 1382: 
 1383: sub start_filterfunc {
 1384:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1385: 
 1386:     if ($target ne 'helper') {
 1387:         return '';
 1388:     }
 1389: 
 1390:     my $contents = Apache::lonxml::get_all_text('/filterfunc',
 1391:                                                 $parser);
 1392:     $contents = 'sub { my $res = shift; ' . $contents . '}';
 1393:     $paramHash->{FILTER_FUNC} = eval $contents;
 1394: }
 1395: 
 1396: sub end_filterfunc { return ''; }
 1397: 
 1398: sub start_choicefunc {
 1399:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1400: 
 1401:     if ($target ne 'helper') {
 1402:         return '';
 1403:     }
 1404: 
 1405:     my $contents = Apache::lonxml::get_all_text('/choicefunc',
 1406:                                                 $parser);
 1407:     $contents = 'sub { my $res = shift; ' . $contents . '}';
 1408:     $paramHash->{CHOICE_FUNC} = eval $contents;
 1409: }
 1410: 
 1411: sub end_choicefunc { return ''; }
 1412: 
 1413: sub start_valuefunc {
 1414:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1415: 
 1416:     if ($target ne 'helper') {
 1417:         return '';
 1418:     }
 1419: 
 1420:     my $contents = Apache::lonxml::get_all_text('/valuefunc',
 1421:                                                 $parser);
 1422:     $contents = 'sub { my $res = shift; ' . $contents . '}';
 1423:     $paramHash->{VALUE_FUNC} = eval $contents;
 1424: }
 1425: 
 1426: sub end_valuefunc { return ''; }
 1427: 
 1428: sub start_mapurl {
 1429:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1430: 
 1431:     if ($target ne 'helper') {
 1432:         return '';
 1433:     }
 1434: 
 1435:     my $contents = Apache::lonxml::get_all_text('/mapurl',
 1436:                                                 $parser);
 1437:     $paramHash->{MAP_URL} = eval $contents;
 1438: }
 1439: 
 1440: sub end_mapurl { return ''; }
 1441: 
 1442: # A note, in case I don't get to this before I leave.
 1443: # If someone complains about the "Back" button returning them
 1444: # to the previous folder state, instead of returning them to
 1445: # the previous helper state, the *correct* answer is for the helper
 1446: # to keep track of how many times the user has manipulated the folders,
 1447: # and feed that to the history.go() call in the helper rendering routines.
 1448: # If done correctly, the helper itself can keep track of how many times
 1449: # it renders the same states, so it doesn't go in just this state, and
 1450: # you can lean on the browser back button to make sure it all chains
 1451: # correctly.
 1452: # Right now, though, I'm just forcing all folders open.
 1453: 
 1454: sub render {
 1455:     my $self = shift;
 1456:     my $result = "";
 1457:     my $var = $self->{'variable'};
 1458:     my $curVal = $helper->{VARS}->{$var};
 1459: 
 1460:     if (defined $self->{ERROR_MSG}) {
 1461:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 1462:     }
 1463: 
 1464:     my $filterFunc = $self->{FILTER_FUNC};
 1465:     my $choiceFunc = $self->{CHOICE_FUNC};
 1466:     my $valueFunc = $self->{VALUE_FUNC};
 1467:     my $mapUrl = $self->{MAP_URL};
 1468: 
 1469:     # Create the composite function that renders the column on the nav map
 1470:     # have to admit any language that lets me do this can't be all bad
 1471:     #  - Jeremy (Pythonista) ;-)
 1472:     my $checked = 0;
 1473:     my $renderColFunc = sub {
 1474:         my ($resource, $part, $params) = @_;
 1475:         
 1476:         if (!&$choiceFunc($resource)) {
 1477:             return '<td>&nbsp;</td>';
 1478:         } else {
 1479:             my $col = "<td><input type='radio' name='${var}.forminput' ";
 1480:             if (!$checked) {
 1481:                 $col .= "checked ";
 1482:                 $checked = 1;
 1483:             }
 1484:             $col .= "value='" . 
 1485:                 HTML::Entities::encode(&$valueFunc($resource)) 
 1486:                 . "' /></td>";
 1487:             return $col;
 1488:         }
 1489:     };
 1490: 
 1491:     $ENV{'form.condition'} = 1;
 1492:     $result .= 
 1493:         &Apache::lonnavmaps::render( { 'cols' => [$renderColFunc, 
 1494:                                                   Apache::lonnavmaps::resource()],
 1495:                                        'showParts' => 0,
 1496:                                        'filterFunc' => $filterFunc,
 1497:                                        'resource_no_folder_link' => 1,
 1498:                                        'iterator_map' => $mapUrl }
 1499:                                        );
 1500:                                                 
 1501:     return $result;
 1502: }
 1503:     
 1504: sub postprocess {
 1505:     my $self = shift;
 1506:     if (defined($self->{NEXTSTATE})) {
 1507:         $helper->changeState($self->{NEXTSTATE});
 1508:     }
 1509: 
 1510:     return 1;
 1511: }
 1512: 
 1513: 1;
 1514: 
 1515: package Apache::lonhelper::student;
 1516: 
 1517: =pod
 1518: 
 1519: =head2 Element: student
 1520: 
 1521: Student elements display a choice of students enrolled in the current
 1522: course. Currently it is primitive; this is expected to evolve later.
 1523: 
 1524: Student elements take two attributes: "variable", which means what
 1525: it usually does, and "multichoice", which if true allows the user
 1526: to select multiple students.
 1527: 
 1528: =cut
 1529: 
 1530: no strict;
 1531: @ISA = ("Apache::lonhelper::element");
 1532: use strict;
 1533: 
 1534: 
 1535: 
 1536: BEGIN {
 1537:     &Apache::lonhelper::register('Apache::lonhelper::student',
 1538:                               ('student'));
 1539: }
 1540: 
 1541: sub new {
 1542:     my $ref = Apache::lonhelper::element->new();
 1543:     bless($ref);
 1544: }
 1545: 
 1546: sub start_student {
 1547:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1548: 
 1549:     if ($target ne 'helper') {
 1550:         return '';
 1551:     }
 1552: 
 1553:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1554:     $helper->declareVar($paramHash->{'variable'});
 1555:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 1556:     if (defined($token->[2]{'nextstate'})) {
 1557:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
 1558:     }
 1559:     
 1560: }    
 1561: 
 1562: sub end_student {
 1563:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1564: 
 1565:     if ($target ne 'helper') {
 1566:         return '';
 1567:     }
 1568:     Apache::lonhelper::student->new();
 1569: }
 1570: 
 1571: sub render {
 1572:     my $self = shift;
 1573:     my $result = '';
 1574:     my $buttons = '';
 1575: 
 1576:     if ($self->{'multichoice'}) {
 1577:         $result = <<SCRIPT;
 1578: <script>
 1579:     function checkall(value) {
 1580: 	for (i=0; i<document.forms.wizform.elements.length; i++) {
 1581:             document.forms.wizform.elements[i].checked=value;
 1582:         }
 1583:     }
 1584: </script>
 1585: SCRIPT
 1586:         $buttons = <<BUTTONS;
 1587: <br />
 1588: <input type="button" onclick="checkall(true)" value="Select All" />
 1589: <input type="button" onclick="checkall(false)" value="Unselect All" />
 1590: <br />
 1591: BUTTONS
 1592:     }
 1593: 
 1594:     if (defined $self->{ERROR_MSG}) {
 1595:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 1596:     }
 1597: 
 1598:     # Load up the students
 1599:     my $choices = &Apache::loncoursedata::get_classlist();
 1600:     my @keys = keys %{$choices};
 1601: 
 1602:     # Constants
 1603:     my $section = Apache::loncoursedata::CL_SECTION();
 1604:     my $fullname = Apache::loncoursedata::CL_FULLNAME();
 1605: 
 1606:     # Sort by: Section, name
 1607:     @keys = sort {
 1608:         if ($choices->{$a}->[$section] ne $choices->{$b}->[$section]) {
 1609:             return $choices->{$a}->[$section] cmp $choices->{$b}->[$section];
 1610:         }
 1611:         return $choices->{$a}->[$fullname] cmp $choices->{$b}->[$fullname];
 1612:     } @keys;
 1613: 
 1614:     my $type = 'radio';
 1615:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
 1616:     $result .= "<table cellspacing='2' cellpadding='2' border='0'>\n";
 1617:     $result .= "<tr><td></td><td align='center'><b>Student Name</b></td>".
 1618:         "<td align='center'><b>Section</b></td></tr>";
 1619: 
 1620:     my $checked = 0;
 1621:     foreach (@keys) {
 1622:         $result .= "<tr><td><input type='$type' name='" .
 1623:             $self->{'variable'} . '.forminput' . "'";
 1624:             
 1625:         if (!$self->{'multichoice'} && !$checked) {
 1626:             $result .= " checked ";
 1627:             $checked = 1;
 1628:         }
 1629:         $result .=
 1630:             " value='" . HTML::Entities::encode($_)
 1631:             . "' /></td><td>"
 1632:             . HTML::Entities::encode($choices->{$_}->[$fullname])
 1633:             . "</td><td align='center'>" 
 1634:             . HTML::Entities::encode($choices->{$_}->[$section])
 1635:             . "</td></tr>\n";
 1636:     }
 1637: 
 1638:     $result .= "</table>\n\n";
 1639:     $result .= $buttons;    
 1640:     
 1641:     return $result;
 1642: }
 1643: 
 1644: sub postprocess {
 1645:     my $self = shift;
 1646: 
 1647:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
 1648:     if (!$result) {
 1649:         $self->{ERROR_MSG} = 'You must choose at least one student '.
 1650:             'to continue.';
 1651:         return 0;
 1652:     }
 1653: 
 1654:     if ($self->{'multichoice'}) {
 1655:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
 1656:                                         $self->{'variable'});
 1657:     }
 1658:     if (defined($self->{NEXTSTATE})) {
 1659:         $helper->changeState($self->{NEXTSTATE});
 1660:     }
 1661: 
 1662:     return 1;
 1663: }
 1664: 
 1665: 1;
 1666: 
 1667: package Apache::lonhelper::files;
 1668: 
 1669: =pod
 1670: 
 1671: =head2 Element: files
 1672: 
 1673: files allows the users to choose files from a given directory on the
 1674: server. It is always multichoice and stores the result as a triple-pipe
 1675: delimited entry in the helper variables. 
 1676: 
 1677: Since it is extremely unlikely that you can actually code a constant
 1678: representing the directory you wish to allow the user to search, <files>
 1679: takes a subroutine that returns the name of the directory you wish to
 1680: have the user browse.
 1681: 
 1682: files accepts the attribute "variable" to control where the files chosen
 1683: are put. It accepts the attribute "multichoice" as the other attribute,
 1684: defaulting to false, which if true will allow the user to select more
 1685: then one choice. 
 1686: 
 1687: <files> accepts three subtags. One is the "nextstate" sub-tag that works
 1688: as it does with the other tags. Another is a <filechoice> sub tag that
 1689: is Perl code that, when surrounded by "sub {" and "}" will return a
 1690: string representing what directory on the server to allow the user to 
 1691: choose files from. Finally, the <filefilter> subtag should contain Perl
 1692: code that when surrounded by "sub { my $filename = shift; " and "}",
 1693: returns a true value if the user can pick that file, or false otherwise.
 1694: The filename passed to the function will be just the name of the file, 
 1695: with no path info.
 1696: 
 1697: =cut
 1698: 
 1699: no strict;
 1700: @ISA = ("Apache::lonhelper::element");
 1701: use strict;
 1702: 
 1703: BEGIN {
 1704:     &Apache::lonhelper::register('Apache::lonhelper::files',
 1705:                                  ('files', 'filechoice', 'filefilter'));
 1706: }
 1707: 
 1708: sub new {
 1709:     my $ref = Apache::lonhelper::element->new();
 1710:     bless($ref);
 1711: }
 1712: 
 1713: sub start_files {
 1714:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1715: 
 1716:     if ($target ne 'helper') {
 1717:         return '';
 1718:     }
 1719:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1720:     $helper->declareVar($paramHash->{'variable'});
 1721:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 1722: }    
 1723: 
 1724: sub end_files {
 1725:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1726: 
 1727:     if ($target ne 'helper') {
 1728:         return '';
 1729:     }
 1730:     if (!defined($paramHash->{FILTER_FUNC})) {
 1731:         $paramHash->{FILTER_FUNC} = sub { return 1; };
 1732:     }
 1733:     Apache::lonhelper::files->new();
 1734: }    
 1735: 
 1736: sub start_filechoice {
 1737:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1738: 
 1739:     if ($target ne 'helper') {
 1740:         return '';
 1741:     }
 1742:     $paramHash->{'filechoice'} = Apache::lonxml::get_all_text('/filechoice',
 1743:                                                               $parser);
 1744: }
 1745: 
 1746: sub end_filechoice { return ''; }
 1747: 
 1748: sub start_filefilter {
 1749:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1750: 
 1751:     if ($target ne 'helper') {
 1752:         return '';
 1753:     }
 1754: 
 1755:     my $contents = Apache::lonxml::get_all_text('/filefilter',
 1756:                                                 $parser);
 1757:     $contents = 'sub { my $filename = shift; ' . $contents . '}';
 1758:     $paramHash->{FILTER_FUNC} = eval $contents;
 1759: }
 1760: 
 1761: sub end_filefilter { return ''; }
 1762: 
 1763: sub render {
 1764:     my $self = shift;
 1765:     my $result = '';
 1766:     my $var = $self->{'variable'};
 1767:     
 1768:     my $subdirFunc = eval('sub {' . $self->{'filechoice'} . '}');
 1769:     die 'Error in resource filter code for variable ' . 
 1770:         {'variable'} . ', Perl said:' . $@ if $@;
 1771: 
 1772:     my $subdir = &$subdirFunc();
 1773: 
 1774:     my $filterFunc = $self->{FILTER_FUNC};
 1775:     my $buttons = '';
 1776: 
 1777:     if ($self->{'multichoice'}) {
 1778:         $result = <<SCRIPT;
 1779: <script>
 1780:     function checkall(value) {
 1781: 	for (i=0; i<document.forms.wizform.elements.length; i++) {
 1782:             ele = document.forms.wizform.elements[i];
 1783:             if (ele.type == "checkbox") {
 1784:                 document.forms.wizform.elements[i].checked=value;
 1785:             }
 1786:         }
 1787:     }
 1788: </script>
 1789: SCRIPT
 1790:         my $buttons = <<BUTTONS;
 1791: <br /> &nbsp;
 1792: <input type="button" onclick="checkall(true)" value="Select All" />
 1793: <input type="button" onclick="checkall(false)" value="Unselect All" />
 1794: <br /> &nbsp;
 1795: BUTTONS
 1796:     }
 1797: 
 1798:     # Get the list of files in this directory.
 1799:     my @fileList;
 1800: 
 1801:     # If the subdirectory is in local CSTR space
 1802:     if ($subdir =~ m|/home/([^/]+)/public_html|) {
 1803:         my $user = $1;
 1804:         my $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 1805:         @fileList = &Apache::lonnet::dirlist($subdir, $domain, $user, '');
 1806:     } else {
 1807:         # local library server resource space
 1808:         @fileList = &Apache::lonnet::dirlist($subdir, $ENV{'user.domain'}, $ENV{'user.name'}, '');
 1809:     }
 1810: 
 1811:     $result .= $buttons;
 1812: 
 1813:     if (defined $self->{ERROR_MSG}) {
 1814:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 1815:     }
 1816: 
 1817:     $result .= '<table border="0" cellpadding="1" cellspacing="1">';
 1818: 
 1819:     # Keeps track if there are no choices, prints appropriate error
 1820:     # if there are none. 
 1821:     my $choices = 0;
 1822:     my $type = 'radio';
 1823:     if ($self->{'multichoice'}) {
 1824:         $type = 'checkbox';
 1825:     }
 1826:     # Print each legitimate file choice.
 1827:     for my $file (@fileList) {
 1828:         $file = (split(/&/, $file))[0];
 1829:         if ($file eq '.' || $file eq '..') {
 1830:             next;
 1831:         }
 1832:         my $fileName = $subdir .'/'. $file;
 1833:         if (&$filterFunc($file)) {
 1834:             $result .= '<tr><td align="right">' .
 1835:                 "<input type='$type' name='" . $var
 1836:             . ".forminput' value='" . HTML::Entities::encode($fileName) .
 1837:                 "'";
 1838:             if (!$self->{'multichoice'} && $choices == 0) {
 1839:                 $result .= ' checked';
 1840:             }
 1841:             $result .= "/></td><td>" . $file . "</td></tr>\n";
 1842:             $choices++;
 1843:         }
 1844:     }
 1845: 
 1846:     $result .= "</table>\n";
 1847: 
 1848:     if (!$choices) {
 1849:         $result .= '<font color="#FF0000">There are no files available to select in this directory. Please go back and select another option.</font><br /><br />';
 1850:     }
 1851: 
 1852:     $result .= $buttons;
 1853: 
 1854:     return $result;
 1855: }
 1856: 
 1857: sub postprocess {
 1858:     my $self = shift;
 1859:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
 1860:     if (!$result) {
 1861:         $self->{ERROR_MSG} = 'You must choose at least one file '.
 1862:             'to continue.';
 1863:         return 0;
 1864:     }
 1865: 
 1866:     if ($self->{'multichoice'}) {
 1867:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
 1868:                                         $self->{'variable'});
 1869:     }
 1870:     if (defined($self->{NEXTSTATE})) {
 1871:         $helper->changeState($self->{NEXTSTATE});
 1872:     }
 1873: 
 1874:     return 1;
 1875: }
 1876: 
 1877: 1;
 1878: 
 1879: package Apache::lonhelper::section;
 1880: 
 1881: =pod
 1882: 
 1883: =head2 Element: section
 1884: 
 1885: <section> allows the user to choose one or more sections from the current
 1886: course.
 1887: 
 1888: It takes the standard attributes "variable", "multichoice", and
 1889: "nextstate", meaning what they do for most other elements.
 1890: 
 1891: =cut
 1892: 
 1893: no strict;
 1894: @ISA = ("Apache::lonhelper::choices");
 1895: use strict;
 1896: 
 1897: BEGIN {
 1898:     &Apache::lonhelper::register('Apache::lonhelper::section',
 1899:                                  ('section'));
 1900: }
 1901: 
 1902: sub new {
 1903:     my $ref = Apache::lonhelper::choices->new();
 1904:     bless($ref);
 1905: }
 1906: 
 1907: sub start_section {
 1908:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1909: 
 1910:     if ($target ne 'helper') {
 1911:         return '';
 1912:     }
 1913: 
 1914:     $paramHash->{CHOICES} = [];
 1915: 
 1916:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1917:     $helper->declareVar($paramHash->{'variable'});
 1918:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 1919:     if (defined($token->[2]{'nextstate'})) {
 1920:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
 1921:     }
 1922: 
 1923:     # Populate the CHOICES element
 1924:     my %choices;
 1925: 
 1926:     my $section = Apache::loncoursedata::CL_SECTION();
 1927:     my $classlist = Apache::loncoursedata::get_classlist();
 1928:     foreach (keys %$classlist) {
 1929:         my $sectionName = $classlist->{$_}->[$section];
 1930:         if (!$sectionName) {
 1931:             $choices{"No section assigned"} = "";
 1932:         } else {
 1933:             $choices{$sectionName} = $sectionName;
 1934:         }
 1935:     } 
 1936:    
 1937:     for my $sectionName (sort(keys(%choices))) {
 1938:         
 1939:         push @{$paramHash->{CHOICES}}, [$sectionName, $sectionName];
 1940:     }
 1941: }    
 1942: 
 1943: sub end_section {
 1944:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1945: 
 1946:     if ($target ne 'helper') {
 1947:         return '';
 1948:     }
 1949:     Apache::lonhelper::section->new();
 1950: }    
 1951: 1;
 1952: 
 1953: package Apache::lonhelper::general;
 1954: 
 1955: =pod
 1956: 
 1957: =head2 General-purpose tag: <exec>
 1958: 
 1959: The contents of the exec tag are executed as Perl code, not inside a 
 1960: safe space, so the full range of $ENV and such is available. The code
 1961: will be executed as a subroutine wrapped with the following code:
 1962: 
 1963: "sub { my $helper = shift; my $state = shift;" and
 1964: 
 1965: "}"
 1966: 
 1967: The return value is ignored.
 1968: 
 1969: $helper is the helper object. Feel free to add methods to the helper
 1970: object to support whatever manipulation you may need to do (for instance,
 1971: overriding the form location if the state is the final state; see 
 1972: lonparm.helper for an example).
 1973: 
 1974: $state is the $paramHash that has currently been generated and may
 1975: be manipulated by the code in exec. Note that the $state is not yet
 1976: an actual state B<object>, it is just a hash, so do not expect to
 1977: be able to call methods on it.
 1978: 
 1979: =cut
 1980: 
 1981: BEGIN {
 1982:     &Apache::lonhelper::register('Apache::lonhelper::general',
 1983:                                  'exec', 'condition', 'clause',
 1984:                                  'eval');
 1985: }
 1986: 
 1987: sub start_exec {
 1988:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1989: 
 1990:     if ($target ne 'helper') {
 1991:         return '';
 1992:     }
 1993:     
 1994:     my $code = &Apache::lonxml::get_all_text('/exec', $parser);
 1995:     
 1996:     $code = eval ('sub { my $helper = shift; my $state = shift; ' .
 1997:         $code . "}");
 1998:     die 'Error in <exec>, Perl said: '. $@ if $@;
 1999:     &$code($helper, $paramHash);
 2000: }
 2001: 
 2002: sub end_exec { return ''; }
 2003: 
 2004: =pod
 2005: 
 2006: =head2 General-purpose tag: <condition>
 2007: 
 2008: The <condition> tag allows you to mask out parts of the helper code
 2009: depending on some programatically determined condition. The condition
 2010: tag contains a tag <clause> which contains perl code that when wrapped
 2011: with "sub { my $helper = shift; my $state = shift; " and "}", returns
 2012: a true value if the XML in the condition should be evaluated as a normal
 2013: part of the helper, or false if it should be completely discarded.
 2014: 
 2015: The <clause> tag must be the first sub-tag of the <condition> tag or
 2016: it will not work as expected.
 2017: 
 2018: =cut
 2019: 
 2020: # The condition tag just functions as a marker, it doesn't have
 2021: # to "do" anything. Technically it doesn't even have to be registered
 2022: # with the lonxml code, but I leave this here to be explicit about it.
 2023: sub start_condition { return ''; }
 2024: sub end_condition { return ''; }
 2025: 
 2026: sub start_clause {
 2027:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2028: 
 2029:     if ($target ne 'helper') {
 2030:         return '';
 2031:     }
 2032:     
 2033:     my $clause = Apache::lonxml::get_all_text('/clause', $parser);
 2034:     $clause = eval('sub { my $helper = shift; my $state = shift; '
 2035:         . $clause . '}');
 2036:     die 'Error in clause of condition, Perl said: ' . $@ if $@;
 2037:     if (!&$clause($helper, $paramHash)) {
 2038:         # Discard all text until the /condition.
 2039:         &Apache::lonxml::get_all_text('/condition', $parser);
 2040:     }
 2041: }
 2042: 
 2043: sub end_clause { return ''; }
 2044: 
 2045: =pod
 2046: 
 2047: =head2 General-purpose tag: <eval>
 2048: 
 2049: The <eval> tag will be evaluated as a subroutine call passed in the
 2050: current helper object and state hash as described in <condition> above,
 2051: but is expected to return a string to be printed directly to the
 2052: screen. This is useful for dynamically generating messages. 
 2053: 
 2054: =cut
 2055: 
 2056: # This is basically a type of message.
 2057: # Programmatically setting $paramHash->{NEXTSTATE} would work, though
 2058: # it's probably bad form.
 2059: 
 2060: sub start_eval {
 2061:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2062: 
 2063:     if ($target ne 'helper') {
 2064:         return '';
 2065:     }
 2066:     
 2067:     my $program = Apache::lonxml::get_all_text('/eval', $parser);
 2068:     $program = eval('sub { my $helper = shift; my $state = shift; '
 2069:         . $program . '}');
 2070:     die 'Error in eval code, Perl said: ' . $@ if $@;
 2071:     $paramHash->{MESSAGE_TEXT} = &$program($helper, $paramHash);
 2072: }
 2073: 
 2074: sub end_eval { 
 2075:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2076: 
 2077:     if ($target ne 'helper') {
 2078:         return '';
 2079:     }
 2080: 
 2081:     Apache::lonhelper::message->new();
 2082: }
 2083: 
 2084: 1;
 2085: 
 2086: package Apache::lonhelper::parmwizfinal;
 2087: 
 2088: # This is the final state for the parmwizard. It is not generally useful,
 2089: # so it is not perldoc'ed. It does its own processing.
 2090: # It is represented with <parmwizfinal />, and
 2091: # should later be moved to lonparmset.pm .
 2092: 
 2093: no strict;
 2094: @ISA = ('Apache::lonhelper::element');
 2095: use strict;
 2096: 
 2097: BEGIN {
 2098:     &Apache::lonhelper::register('Apache::lonhelper::parmwizfinal',
 2099:                                  ('parmwizfinal'));
 2100: }
 2101: 
 2102: use Time::localtime;
 2103: 
 2104: sub new {
 2105:     my $ref = Apache::lonhelper::choices->new();
 2106:     bless ($ref);
 2107: }
 2108: 
 2109: sub start_parmwizfinal { return ''; }
 2110: 
 2111: sub end_parmwizfinal {
 2112:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2113: 
 2114:     if ($target ne 'helper') {
 2115:         return '';
 2116:     }
 2117:     Apache::lonhelper::parmwizfinal->new();
 2118: }
 2119: 
 2120: # Renders a form that, when submitted, will form the input to lonparmset.pm
 2121: sub render {
 2122:     my $self = shift;
 2123:     my $vars = $helper->{VARS};
 2124: 
 2125:     # FIXME: Unify my designators with the standard ones
 2126:     my %dateTypeHash = ('open_date' => "Opening Date",
 2127:                         'due_date' => "Due Date",
 2128:                         'answer_date' => "Answer Date");
 2129:     my %parmTypeHash = ('open_date' => "0_opendate",
 2130:                         'due_date' => "0_duedate",
 2131:                         'answer_date' => "0_answerdate");
 2132:     
 2133:     my $result = "<form name='wizform' method='get' action='/adm/parmset'>\n";
 2134:     $result .= '<p>Confirm that this information is correct, then click &quot;Finish Wizard&quot; to complete setting the parameter.<ul>';
 2135:     my $affectedResourceId = "";
 2136:     my $parm_name = $parmTypeHash{$vars->{ACTION_TYPE}};
 2137:     my $level = "";
 2138:     
 2139:     # Print the type of manipulation:
 2140:     $result .= '<li>Setting the <b>' . $dateTypeHash{$vars->{ACTION_TYPE}}
 2141:                . "</b></li>\n";
 2142:     if ($vars->{ACTION_TYPE} eq 'due_date' || 
 2143:         $vars->{ACTION_TYPE} eq 'answer_date') {
 2144:         # for due dates, we default to "date end" type entries
 2145:         $result .= "<input type='hidden' name='recent_date_end' " .
 2146:             "value='" . $vars->{PARM_DATE} . "' />\n";
 2147:         $result .= "<input type='hidden' name='pres_value' " . 
 2148:             "value='" . $vars->{PARM_DATE} . "' />\n";
 2149:         $result .= "<input type='hidden' name='pres_type' " .
 2150:             "value='date_end' />\n";
 2151:     } elsif ($vars->{ACTION_TYPE} eq 'open_date') {
 2152:         $result .= "<input type='hidden' name='recent_date_start' ".
 2153:             "value='" . $vars->{PARM_DATE} . "' />\n";
 2154:         $result .= "<input type='hidden' name='pres_value' " .
 2155:             "value='" . $vars->{PARM_DATE} . "' />\n";
 2156:         $result .= "<input type='hidden' name='pres_type' " .
 2157:             "value='date_start' />\n";
 2158:     } 
 2159:     
 2160:     # Print the granularity, depending on the action
 2161:     if ($vars->{GRANULARITY} eq 'whole_course') {
 2162:         $result .= '<li>for <b>all resources in the course</b></li>';
 2163:         $level = 9; # general course, see lonparmset.pm perldoc
 2164:         $affectedResourceId = "0.0";
 2165:     } elsif ($vars->{GRANULARITY} eq 'map') {
 2166:         my $navmap = Apache::lonnavmaps::navmap->new(
 2167:                            $ENV{"request.course.fn"}.".db",
 2168:                            $ENV{"request.course.fn"}."_parms.db", 0, 0);
 2169:         my $res = $navmap->getById($vars->{RESOURCE_ID});
 2170:         my $title = $res->compTitle();
 2171:         $navmap->untieHashes();
 2172:         $result .= "<li>for the map named <b>$title</b></li>";
 2173:         $level = 8;
 2174:         $affectedResourceId = $vars->{RESOURCE_ID};
 2175:     } else {
 2176:         my $navmap = Apache::lonnavmaps::navmap->new(
 2177:                            $ENV{"request.course.fn"}.".db",
 2178:                            $ENV{"request.course.fn"}."_parms.db", 0, 0);
 2179:         my $res = $navmap->getById($vars->{RESOURCE_ID});
 2180:         my $title = $res->compTitle();
 2181:         $navmap->untieHashes();
 2182:         $result .= "<li>for the resource named <b>$title</b></li>";
 2183:         $level = 7;
 2184:         $affectedResourceId = $vars->{RESOURCE_ID};
 2185:     }
 2186: 
 2187:     # Print targets
 2188:     if ($vars->{TARGETS} eq 'course') {
 2189:         $result .= '<li>for <b>all students in course</b></li>';
 2190:     } elsif ($vars->{TARGETS} eq 'section') {
 2191:         my $section = $vars->{SECTION_NAME};
 2192:         $result .= "<li>for section <b>$section</b></li>";
 2193:         $level -= 3;
 2194:         $result .= "<input type='hidden' name='csec' value='" .
 2195:             HTML::Entities::encode($section) . "' />\n";
 2196:     } else {
 2197:         # FIXME: This is probably wasteful! Store the name!
 2198:         my $classlist = Apache::loncoursedata::get_classlist();
 2199:         my $name = $classlist->{$vars->{USER_NAME}}->[6];
 2200:         $result .= "<li>for <b>$name</b></li>";
 2201:         $level -= 6;
 2202:         my ($uname, $udom) = split /:/, $vars->{USER_NAME};
 2203:         $result .= "<input type='hidden' name='uname' value='".
 2204:             HTML::Entities::encode($uname) . "' />\n";
 2205:         $result .= "<input type='hidden' name='udom' value='".
 2206:             HTML::Entities::encode($udom) . "' />\n";
 2207:     }
 2208: 
 2209:     # Print value
 2210:     $result .= "<li>to <b>" . ctime($vars->{PARM_DATE}) . "</b> (" .
 2211:         Apache::lonnavmaps::timeToHumanString($vars->{PARM_DATE}) 
 2212:         . ")</li>\n";
 2213: 
 2214:     # print pres_marker
 2215:     $result .= "\n<input type='hidden' name='pres_marker'" .
 2216:         " value='$affectedResourceId&$parm_name&$level' />\n";
 2217: 
 2218:     $result .= "<br /><br /><center><input type='submit' value='Finish Helper' /></center></form>\n";
 2219: 
 2220:     return $result;
 2221: }
 2222:     
 2223: sub overrideForm {
 2224:     return 1;
 2225: }
 2226: 
 2227: 1;
 2228: 
 2229: __END__
 2230: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>