File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.17: download - view: text, annotated - select for diffs
Fri May 2 19:20:51 2003 UTC (21 years, 1 month ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Resource panels have new options "toponly" to avoid recursion.

Enhanced documentation for creating helpers by code.

Fixed some features with the preprocessing that was supposed to work;
states are supposed to have the opportunity to bypass themselves. The
page format element does this (if the user did not select one col, it
skips itself). For a variety of reasons this was not working.

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

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