File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.24: download - view: text, annotated - select for diffs
Thu May 8 19:17:31 2003 UTC (21 years, 1 month ago) by sakharuk
Branches: MAIN
CVS tags: HEAD
 Small check where we are (construction space or resources space) added.

    1: # The LearningOnline Network with CAPA
    2: # .helper XML handler to implement the LON-CAPA helper
    3: #
    4: # $Id: lonhelper.pm,v 1.24 2003/05/08 19:17:31 sakharuk 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'} if (!defined($paramHash->{'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, checkName) {
 1001: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
 1002:             ele = document.forms.helpform.elements[i];
 1003:             if (ele.name == checkName + '.forminput') {
 1004:                 document.forms.helpform.elements[i].checked=value;
 1005:             }
 1006:         }
 1007:     }
 1008: </script>
 1009: SCRIPT
 1010:         $buttons = <<BUTTONS;
 1011: <br />
 1012: <input type="button" onclick="checkall(true, '$var')" value="Select All" />
 1013: <input type="button" onclick="checkall(false, '$var')" value="Unselect All" />
 1014: <br />&nbsp;
 1015: BUTTONS
 1016:     }
 1017: 
 1018:     if (defined $self->{ERROR_MSG}) {
 1019:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br />';
 1020:     }
 1021: 
 1022:     $result .= $buttons;
 1023:     
 1024:     $result .= "<table>\n\n";
 1025: 
 1026:     my $type = "radio";
 1027:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
 1028:     my $checked = 0;
 1029:     foreach my $choice (@{$self->{CHOICES}}) {
 1030:         $result .= "<tr>\n<td width='20'>&nbsp;</td>\n";
 1031:         $result .= "<td valign='top'><input type='$type' name='$var.forminput'"
 1032:             . "' value='" . 
 1033:             HTML::Entities::encode($choice->[1]) 
 1034:             . "'";
 1035:         if (!$self->{'multichoice'} && !$checked) {
 1036:             $result .= " checked ";
 1037:             $checked = 1;
 1038:         }
 1039:         my $choiceLabel = $choice->[0];
 1040:         if ($choice->[4]) {  # if we need to evaluate this choice
 1041:             $choiceLabel = "sub { my $helper = shift; my $state = shift;" .
 1042:                 $choiceLabel . "}";
 1043:             $choiceLabel = eval($choiceLabel);
 1044:             $choiceLabel = &$choiceLabel($helper, $self);
 1045:         }
 1046:         $result .= "/></td><td> " . $choiceLabel . "</td></tr>\n";
 1047:     }
 1048:     $result .= "</table>\n\n\n";
 1049:     $result .= $buttons;
 1050: 
 1051:     return $result;
 1052: }
 1053: 
 1054: # If a NEXTSTATE was given or a nextstate for this choice was
 1055: # given, switch to it
 1056: sub postprocess {
 1057:     my $self = shift;
 1058:     my $chosenValue = $ENV{'form.' . $self->{'variable'} . '.forminput'};
 1059: 
 1060:     if (!$chosenValue) {
 1061:         $self->{ERROR_MSG} = "You must choose one or more choices to" .
 1062:             " continue.";
 1063:         return 0;
 1064:     }
 1065: 
 1066:     if ($self->{'multichoice'}) {
 1067:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
 1068:                                         $self->{'variable'});
 1069:     }
 1070: 
 1071:     if (defined($self->{NEXTSTATE})) {
 1072:         $helper->changeState($self->{NEXTSTATE});
 1073:     }
 1074:     
 1075:     foreach my $choice (@{$self->{CHOICES}}) {
 1076:         if ($choice->[1] eq $chosenValue) {
 1077:             if (defined($choice->[2])) {
 1078:                 $helper->changeState($choice->[2]);
 1079:             }
 1080:         }
 1081:     }
 1082:     return 1;
 1083: }
 1084: 1;
 1085: 
 1086: package Apache::lonhelper::date;
 1087: 
 1088: =pod
 1089: 
 1090: =head2 Element: date
 1091: 
 1092: Date elements allow the selection of a date with a drop down list.
 1093: 
 1094: Date elements can take two attributes:
 1095: 
 1096: =over 4
 1097: 
 1098: =item * B<variable>: The name of the variable to store the chosen
 1099:         date in. Required.
 1100: 
 1101: =item * B<hoursminutes>: If a true value, the date will show hours
 1102:         and minutes, as well as month/day/year. If false or missing,
 1103:         the date will only show the month, day, and year.
 1104: 
 1105: =back
 1106: 
 1107: Date elements contain only an option <nextstate> tag to determine
 1108: the next state.
 1109: 
 1110: Example:
 1111: 
 1112:  <date variable="DUE_DATE" hoursminutes="1">
 1113:    <nextstate>choose_why</nextstate>
 1114:    </date>
 1115: 
 1116: =cut
 1117: 
 1118: no strict;
 1119: @ISA = ("Apache::lonhelper::element");
 1120: use strict;
 1121: 
 1122: use Time::localtime;
 1123: 
 1124: BEGIN {
 1125:     &Apache::lonhelper::register('Apache::lonhelper::date',
 1126:                               ('date'));
 1127: }
 1128: 
 1129: # Don't need to override the "new" from element
 1130: sub new {
 1131:     my $ref = Apache::lonhelper::element->new();
 1132:     bless($ref);
 1133: }
 1134: 
 1135: my @months = ("January", "February", "March", "April", "May", "June", "July",
 1136: 	      "August", "September", "October", "November", "December");
 1137: 
 1138: # CONSTRUCTION: Construct the message element from the XML
 1139: sub start_date {
 1140:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1141: 
 1142:     if ($target ne 'helper') {
 1143:         return '';
 1144:     }
 1145: 
 1146:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1147:     $helper->declareVar($paramHash->{'variable'});
 1148:     $paramHash->{'hoursminutes'} = $token->[2]{'hoursminutes'};
 1149: }
 1150: 
 1151: sub end_date {
 1152:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1153: 
 1154:     if ($target ne 'helper') {
 1155:         return '';
 1156:     }
 1157:     Apache::lonhelper::date->new();
 1158:     return '';
 1159: }
 1160: 
 1161: sub render {
 1162:     my $self = shift;
 1163:     my $result = "";
 1164:     my $var = $self->{'variable'};
 1165: 
 1166:     my $date;
 1167:     
 1168:     # Default date: The current hour.
 1169:     $date = localtime();
 1170:     $date->min(0);
 1171: 
 1172:     if (defined $self->{ERROR_MSG}) {
 1173:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 1174:     }
 1175: 
 1176:     # Month
 1177:     my $i;
 1178:     $result .= "<select name='${var}month'>\n";
 1179:     for ($i = 0; $i < 12; $i++) {
 1180:         if ($i == $date->mon) {
 1181:             $result .= "<option value='$i' selected>";
 1182:         } else {
 1183:             $result .= "<option value='$i'>";
 1184:         }
 1185:         $result .= $months[$i] . "</option>\n";
 1186:     }
 1187:     $result .= "</select>\n";
 1188: 
 1189:     # Day
 1190:     $result .= "<select name='${var}day'>\n";
 1191:     for ($i = 1; $i < 32; $i++) {
 1192:         if ($i == $date->mday) {
 1193:             $result .= '<option selected>';
 1194:         } else {
 1195:             $result .= '<option>';
 1196:         }
 1197:         $result .= "$i</option>\n";
 1198:     }
 1199:     $result .= "</select>,\n";
 1200: 
 1201:     # Year
 1202:     $result .= "<select name='${var}year'>\n";
 1203:     for ($i = 2000; $i < 2030; $i++) { # update this after 64-bit dates
 1204:         if ($date->year + 1900 == $i) {
 1205:             $result .= "<option selected>";
 1206:         } else {
 1207:             $result .= "<option>";
 1208:         }
 1209:         $result .= "$i</option>\n";
 1210:     }
 1211:     $result .= "</select>,\n";
 1212: 
 1213:     # Display Hours and Minutes if they are called for
 1214:     if ($self->{'hoursminutes'}) {
 1215:         # Build hour
 1216:         $result .= "<select name='${var}hour'>\n";
 1217:         $result .= "<option " . ($date->hour == 0 ? 'selected ':'') .
 1218:             " value='0'>midnight</option>\n";
 1219:         for ($i = 1; $i < 12; $i++) {
 1220:             if ($date->hour == $i) {
 1221:                 $result .= "<option selected value='$i'>$i a.m.</option>\n";
 1222:             } else {
 1223:                 $result .= "<option value='$i'>$i a.m</option>\n";
 1224:             }
 1225:         }
 1226:         $result .= "<option " . ($date->hour == 12 ? 'selected ':'') .
 1227:             " value='12'>noon</option>\n";
 1228:         for ($i = 13; $i < 24; $i++) {
 1229:             my $printedHour = $i - 12;
 1230:             if ($date->hour == $i) {
 1231:                 $result .= "<option selected value='$i'>$printedHour p.m.</option>\n";
 1232:             } else {
 1233:                 $result .= "<option value='$i'>$printedHour p.m.</option>\n";
 1234:             }
 1235:         }
 1236: 
 1237:         $result .= "</select> :\n";
 1238: 
 1239:         $result .= "<select name='${var}minute'>\n";
 1240:         for ($i = 0; $i < 60; $i++) {
 1241:             my $printedMinute = $i;
 1242:             if ($i < 10) {
 1243:                 $printedMinute = "0" . $printedMinute;
 1244:             }
 1245:             if ($date->min == $i) {
 1246:                 $result .= "<option selected>";
 1247:             } else {
 1248:                 $result .= "<option>";
 1249:             }
 1250:             $result .= "$printedMinute</option>\n";
 1251:         }
 1252:         $result .= "</select>\n";
 1253:     }
 1254: 
 1255:     return $result;
 1256: 
 1257: }
 1258: # If a NEXTSTATE was given, switch to it
 1259: sub postprocess {
 1260:     my $self = shift;
 1261:     my $var = $self->{'variable'};
 1262:     my $month = $ENV{'form.' . $var . 'month'}; 
 1263:     my $day = $ENV{'form.' . $var . 'day'}; 
 1264:     my $year = $ENV{'form.' . $var . 'year'}; 
 1265:     my $min = 0; 
 1266:     my $hour = 0;
 1267:     if ($self->{'hoursminutes'}) {
 1268:         $min = $ENV{'form.' . $var . 'minute'};
 1269:         $hour = $ENV{'form.' . $var . 'hour'};
 1270:     }
 1271: 
 1272:     my $chosenDate = Time::Local::timelocal(0, $min, $hour, $day, $month, $year);
 1273:     # Check to make sure that the date was not automatically co-erced into a 
 1274:     # valid date, as we want to flag that as an error
 1275:     # This happens for "Feb. 31", for instance, which is coerced to March 2 or
 1276:     # 3, depending on if it's a leapyear
 1277:     my $checkDate = localtime($chosenDate);
 1278: 
 1279:     if ($checkDate->mon != $month || $checkDate->mday != $day ||
 1280:         $checkDate->year + 1900 != $year) {
 1281:         $self->{ERROR_MSG} = "Can't use " . $months[$month] . " $day, $year as a "
 1282:             . "date because it doesn't exist. Please enter a valid date.";
 1283:         return 0;
 1284:     }
 1285: 
 1286:     $helper->{VARS}->{$var} = $chosenDate;
 1287: 
 1288:     if (defined($self->{NEXTSTATE})) {
 1289:         $helper->changeState($self->{NEXTSTATE});
 1290:     }
 1291: 
 1292:     return 1;
 1293: }
 1294: 1;
 1295: 
 1296: package Apache::lonhelper::resource;
 1297: 
 1298: =pod
 1299: 
 1300: =head2 Element: resource
 1301: 
 1302: <resource> elements allow the user to select one or multiple resources
 1303: from the current course. You can filter out which resources they can view,
 1304: and filter out which resources they can select. The course will always
 1305: be displayed fully expanded, because of the difficulty of maintaining
 1306: selections across folder openings and closings. If this is fixed, then
 1307: the user can manipulate the folders.
 1308: 
 1309: <resource> takes the standard variable attribute to control what helper
 1310: variable stores the results. It also takes a "multichoice" attribute,
 1311: which controls whether the user can select more then one resource. The 
 1312: "toponly" attribute controls whether the resource display shows just the
 1313: resources in that sequence, or recurses into all sub-sequences, defaulting
 1314: to false.
 1315: 
 1316: B<SUB-TAGS>
 1317: 
 1318: =over 4
 1319: 
 1320: =item * <filterfunc>: If you want to filter what resources are displayed
 1321:   to the user, use a filter func. The <filterfunc> tag should contain
 1322:   Perl code that when wrapped with "sub { my $res = shift; " and "}" is 
 1323:   a function that returns true if the resource should be displayed, 
 1324:   and false if it should be skipped. $res is a resource object. 
 1325:   (See Apache::lonnavmaps documentation for information about the 
 1326:   resource object.)
 1327: 
 1328: =item * <choicefunc>: Same as <filterfunc>, except that controls whether
 1329:   the given resource can be chosen. (It is almost always a good idea to
 1330:   show the user the folders, for instance, but you do not always want to 
 1331:   let the user select them.)
 1332: 
 1333: =item * <nextstate>: Standard nextstate behavior.
 1334: 
 1335: =item * <valuefunc>: This function controls what is returned by the resource
 1336:   when the user selects it. Like filterfunc and choicefunc, it should be
 1337:   a function fragment that when wrapped by "sub { my $res = shift; " and
 1338:   "}" returns a string representing what you want to have as the value. By
 1339:   default, the value will be the resource ID of the object ($res->{ID}).
 1340: 
 1341: =item * <mapurl>: If the URL of a map is given here, only that map
 1342:   will be displayed, instead of the whole course.
 1343: 
 1344: =back
 1345: 
 1346: =cut
 1347: 
 1348: no strict;
 1349: @ISA = ("Apache::lonhelper::element");
 1350: use strict;
 1351: 
 1352: BEGIN {
 1353:     &Apache::lonhelper::register('Apache::lonhelper::resource',
 1354:                               ('resource', 'filterfunc', 
 1355:                                'choicefunc', 'valuefunc',
 1356:                                'mapurl'));
 1357: }
 1358: 
 1359: sub new {
 1360:     my $ref = Apache::lonhelper::element->new();
 1361:     bless($ref);
 1362: }
 1363: 
 1364: # CONSTRUCTION: Construct the message element from the XML
 1365: sub start_resource {
 1366:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1367: 
 1368:     if ($target ne 'helper') {
 1369:         return '';
 1370:     }
 1371: 
 1372:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1373:     $helper->declareVar($paramHash->{'variable'});
 1374:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 1375:     $paramHash->{'toponly'} = $token->[2]{'toponly'};
 1376:     return '';
 1377: }
 1378: 
 1379: sub end_resource {
 1380:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1381: 
 1382:     if ($target ne 'helper') {
 1383:         return '';
 1384:     }
 1385:     if (!defined($paramHash->{FILTER_FUNC})) {
 1386:         $paramHash->{FILTER_FUNC} = sub {return 1;};
 1387:     }
 1388:     if (!defined($paramHash->{CHOICE_FUNC})) {
 1389:         $paramHash->{CHOICE_FUNC} = sub {return 1;};
 1390:     }
 1391:     if (!defined($paramHash->{VALUE_FUNC})) {
 1392:         $paramHash->{VALUE_FUNC} = sub {my $res = shift; return $res->{ID}; };
 1393:     }
 1394:     Apache::lonhelper::resource->new();
 1395:     return '';
 1396: }
 1397: 
 1398: sub start_filterfunc {
 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('/filterfunc',
 1406:                                                 $parser);
 1407:     $contents = 'sub { my $res = shift; ' . $contents . '}';
 1408:     $paramHash->{FILTER_FUNC} = eval $contents;
 1409: }
 1410: 
 1411: sub end_filterfunc { return ''; }
 1412: 
 1413: sub start_choicefunc {
 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('/choicefunc',
 1421:                                                 $parser);
 1422:     $contents = 'sub { my $res = shift; ' . $contents . '}';
 1423:     $paramHash->{CHOICE_FUNC} = eval $contents;
 1424: }
 1425: 
 1426: sub end_choicefunc { return ''; }
 1427: 
 1428: sub start_valuefunc {
 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('/valuefunc',
 1436:                                                 $parser);
 1437:     $contents = 'sub { my $res = shift; ' . $contents . '}';
 1438:     $paramHash->{VALUE_FUNC} = eval $contents;
 1439: }
 1440: 
 1441: sub end_valuefunc { return ''; }
 1442: 
 1443: sub start_mapurl {
 1444:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1445: 
 1446:     if ($target ne 'helper') {
 1447:         return '';
 1448:     }
 1449: 
 1450:     my $contents = Apache::lonxml::get_all_text('/mapurl',
 1451:                                                 $parser);
 1452:     $paramHash->{MAP_URL} = $contents;
 1453: }
 1454: 
 1455: sub end_mapurl { return ''; }
 1456: 
 1457: # A note, in case I don't get to this before I leave.
 1458: # If someone complains about the "Back" button returning them
 1459: # to the previous folder state, instead of returning them to
 1460: # the previous helper state, the *correct* answer is for the helper
 1461: # to keep track of how many times the user has manipulated the folders,
 1462: # and feed that to the history.go() call in the helper rendering routines.
 1463: # If done correctly, the helper itself can keep track of how many times
 1464: # it renders the same states, so it doesn't go in just this state, and
 1465: # you can lean on the browser back button to make sure it all chains
 1466: # correctly.
 1467: # Right now, though, I'm just forcing all folders open.
 1468: 
 1469: sub render {
 1470:     my $self = shift;
 1471:     my $result = "";
 1472:     my $var = $self->{'variable'};
 1473:     my $curVal = $helper->{VARS}->{$var};
 1474: 
 1475:     my $buttons = '';
 1476: 
 1477:     if ($self->{'multichoice'}) {
 1478:         $result = <<SCRIPT;
 1479: <script>
 1480:     function checkall(value, checkName) {
 1481: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
 1482:             ele = document.forms.helpform.elements[i];
 1483:             if (ele.name == checkName + '.forminput') {
 1484:                 document.forms.helpform.elements[i].checked=value;
 1485:             }
 1486:         }
 1487:     }
 1488: </script>
 1489: SCRIPT
 1490:         $buttons = <<BUTTONS;
 1491: <br /> &nbsp;
 1492: <input type="button" onclick="checkall(true, '$var')" value="Select All Resources" />
 1493: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Resources" />
 1494: <br /> &nbsp;
 1495: BUTTONS
 1496:     }
 1497: 
 1498:     if (defined $self->{ERROR_MSG}) {
 1499:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 1500:     }
 1501: 
 1502:     $result .= $buttons;
 1503: 
 1504:     my $filterFunc = $self->{FILTER_FUNC};
 1505:     my $choiceFunc = $self->{CHOICE_FUNC};
 1506:     my $valueFunc = $self->{VALUE_FUNC};
 1507:     my $mapUrl = $self->{MAP_URL};
 1508:     my $multichoice = $self->{'multichoice'};
 1509: 
 1510:     # Create the composite function that renders the column on the nav map
 1511:     # have to admit any language that lets me do this can't be all bad
 1512:     #  - Jeremy (Pythonista) ;-)
 1513:     my $checked = 0;
 1514:     my $renderColFunc = sub {
 1515:         my ($resource, $part, $params) = @_;
 1516: 
 1517:         my $inputType;
 1518:         if ($multichoice) { $inputType = 'checkbox'; }
 1519:         else {$inputType = 'radio'; }
 1520: 
 1521:         if (!&$choiceFunc($resource)) {
 1522:             return '<td>&nbsp;</td>';
 1523:         } else {
 1524:             my $col = "<td><input type='$inputType' name='${var}.forminput' ";
 1525:             if (!$checked && !$multichoice) {
 1526:                 $col .= "checked ";
 1527:                 $checked = 1;
 1528:             }
 1529:             $col .= "value='" . 
 1530:                 HTML::Entities::encode(&$valueFunc($resource)) 
 1531:                 . "' /></td>";
 1532:             return $col;
 1533:         }
 1534:     };
 1535: 
 1536:     $ENV{'form.condition'} = !$self->{'toponly'};
 1537:     $result .= 
 1538:         &Apache::lonnavmaps::render( { 'cols' => [$renderColFunc, 
 1539:                                                   Apache::lonnavmaps::resource()],
 1540:                                        'showParts' => 0,
 1541:                                        'filterFunc' => $filterFunc,
 1542:                                        'resource_no_folder_link' => 1,
 1543:                                        'iterator_map' => $mapUrl }
 1544:                                        );
 1545: 
 1546:     $result .= $buttons;
 1547:                                                 
 1548:     return $result;
 1549: }
 1550:     
 1551: sub postprocess {
 1552:     my $self = shift;
 1553: 
 1554:     if ($self->{'multichoice'}) {
 1555:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
 1556:                                         $self->{'variable'});
 1557:     }
 1558: 
 1559:     if ($self->{'multichoice'} && !$helper->{VARS}->{$self->{'variable'}}) {
 1560:         $self->{ERROR_MSG} = 'You must choose at least one resource to continue.';
 1561:         return 0;
 1562:     }
 1563: 
 1564:     if (defined($self->{NEXTSTATE})) {
 1565:         $helper->changeState($self->{NEXTSTATE});
 1566:     }
 1567: 
 1568:     return 1;
 1569: }
 1570: 
 1571: 1;
 1572: 
 1573: package Apache::lonhelper::student;
 1574: 
 1575: =pod
 1576: 
 1577: =head2 Element: student
 1578: 
 1579: Student elements display a choice of students enrolled in the current
 1580: course. Currently it is primitive; this is expected to evolve later.
 1581: 
 1582: Student elements take two attributes: "variable", which means what
 1583: it usually does, and "multichoice", which if true allows the user
 1584: to select multiple students.
 1585: 
 1586: =cut
 1587: 
 1588: no strict;
 1589: @ISA = ("Apache::lonhelper::element");
 1590: use strict;
 1591: 
 1592: 
 1593: 
 1594: BEGIN {
 1595:     &Apache::lonhelper::register('Apache::lonhelper::student',
 1596:                               ('student'));
 1597: }
 1598: 
 1599: sub new {
 1600:     my $ref = Apache::lonhelper::element->new();
 1601:     bless($ref);
 1602: }
 1603: 
 1604: sub start_student {
 1605:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1606: 
 1607:     if ($target ne 'helper') {
 1608:         return '';
 1609:     }
 1610: 
 1611:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1612:     $helper->declareVar($paramHash->{'variable'});
 1613:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 1614:     if (defined($token->[2]{'nextstate'})) {
 1615:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
 1616:     }
 1617:     
 1618: }    
 1619: 
 1620: sub end_student {
 1621:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1622: 
 1623:     if ($target ne 'helper') {
 1624:         return '';
 1625:     }
 1626:     Apache::lonhelper::student->new();
 1627: }
 1628: 
 1629: sub render {
 1630:     my $self = shift;
 1631:     my $result = '';
 1632:     my $buttons = '';
 1633:     my $var = $self->{'variable'};
 1634: 
 1635:     if ($self->{'multichoice'}) {
 1636:         $result = <<SCRIPT;
 1637: <script>
 1638:     function checkall(value, checkName) {
 1639: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
 1640:             ele = document.forms.helpform.elements[i];
 1641:             if (ele.name == checkName + '.forminput') {
 1642:                 document.forms.helpform.elements[i].checked=value;
 1643:             }
 1644:         }
 1645:     }
 1646: </script>
 1647: SCRIPT
 1648:         $buttons = <<BUTTONS;
 1649: <br />
 1650: <input type="button" onclick="checkall(true, '$var')" value="Select All Students" />
 1651: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Students" />
 1652: <br />
 1653: BUTTONS
 1654:     }
 1655: 
 1656:     if (defined $self->{ERROR_MSG}) {
 1657:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 1658:     }
 1659: 
 1660:     # Load up the students
 1661:     my $choices = &Apache::loncoursedata::get_classlist();
 1662:     my @keys = keys %{$choices};
 1663: 
 1664:     # Constants
 1665:     my $section = Apache::loncoursedata::CL_SECTION();
 1666:     my $fullname = Apache::loncoursedata::CL_FULLNAME();
 1667: 
 1668:     # Sort by: Section, name
 1669:     @keys = sort {
 1670:         if ($choices->{$a}->[$section] ne $choices->{$b}->[$section]) {
 1671:             return $choices->{$a}->[$section] cmp $choices->{$b}->[$section];
 1672:         }
 1673:         return $choices->{$a}->[$fullname] cmp $choices->{$b}->[$fullname];
 1674:     } @keys;
 1675: 
 1676:     my $type = 'radio';
 1677:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
 1678:     $result .= "<table cellspacing='2' cellpadding='2' border='0'>\n";
 1679:     $result .= "<tr><td></td><td align='center'><b>Student Name</b></td>".
 1680:         "<td align='center'><b>Section</b></td></tr>";
 1681: 
 1682:     my $checked = 0;
 1683:     foreach (@keys) {
 1684:         $result .= "<tr><td><input type='$type' name='" .
 1685:             $self->{'variable'} . '.forminput' . "'";
 1686:             
 1687:         if (!$self->{'multichoice'} && !$checked) {
 1688:             $result .= " checked ";
 1689:             $checked = 1;
 1690:         }
 1691:         $result .=
 1692:             " value='" . HTML::Entities::encode($_ . ':' . $choices->{$_}->[$section])
 1693:             . "' /></td><td>"
 1694:             . HTML::Entities::encode($choices->{$_}->[$fullname])
 1695:             . "</td><td align='center'>" 
 1696:             . HTML::Entities::encode($choices->{$_}->[$section])
 1697:             . "</td></tr>\n";
 1698:     }
 1699: 
 1700:     $result .= "</table>\n\n";
 1701:     $result .= $buttons;    
 1702:     
 1703:     return $result;
 1704: }
 1705: 
 1706: sub postprocess {
 1707:     my $self = shift;
 1708: 
 1709:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
 1710:     if (!$result) {
 1711:         $self->{ERROR_MSG} = 'You must choose at least one student '.
 1712:             'to continue.';
 1713:         return 0;
 1714:     }
 1715: 
 1716:     if ($self->{'multichoice'}) {
 1717:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
 1718:                                         $self->{'variable'});
 1719:     }
 1720:     if (defined($self->{NEXTSTATE})) {
 1721:         $helper->changeState($self->{NEXTSTATE});
 1722:     }
 1723: 
 1724:     return 1;
 1725: }
 1726: 
 1727: 1;
 1728: 
 1729: package Apache::lonhelper::files;
 1730: 
 1731: =pod
 1732: 
 1733: =head2 Element: files
 1734: 
 1735: files allows the users to choose files from a given directory on the
 1736: server. It is always multichoice and stores the result as a triple-pipe
 1737: delimited entry in the helper variables. 
 1738: 
 1739: Since it is extremely unlikely that you can actually code a constant
 1740: representing the directory you wish to allow the user to search, <files>
 1741: takes a subroutine that returns the name of the directory you wish to
 1742: have the user browse.
 1743: 
 1744: files accepts the attribute "variable" to control where the files chosen
 1745: are put. It accepts the attribute "multichoice" as the other attribute,
 1746: defaulting to false, which if true will allow the user to select more
 1747: then one choice. 
 1748: 
 1749: <files> accepts three subtags. One is the "nextstate" sub-tag that works
 1750: as it does with the other tags. Another is a <filechoice> sub tag that
 1751: is Perl code that, when surrounded by "sub {" and "}" will return a
 1752: string representing what directory on the server to allow the user to 
 1753: choose files from. Finally, the <filefilter> subtag should contain Perl
 1754: code that when surrounded by "sub { my $filename = shift; " and "}",
 1755: returns a true value if the user can pick that file, or false otherwise.
 1756: The filename passed to the function will be just the name of the file, 
 1757: with no path info.
 1758: 
 1759: =cut
 1760: 
 1761: no strict;
 1762: @ISA = ("Apache::lonhelper::element");
 1763: use strict;
 1764: 
 1765: BEGIN {
 1766:     &Apache::lonhelper::register('Apache::lonhelper::files',
 1767:                                  ('files', 'filechoice', 'filefilter'));
 1768: }
 1769: 
 1770: sub new {
 1771:     my $ref = Apache::lonhelper::element->new();
 1772:     bless($ref);
 1773: }
 1774: 
 1775: sub start_files {
 1776:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1777: 
 1778:     if ($target ne 'helper') {
 1779:         return '';
 1780:     }
 1781:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1782:     $helper->declareVar($paramHash->{'variable'});
 1783:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 1784: }    
 1785: 
 1786: sub end_files {
 1787:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1788: 
 1789:     if ($target ne 'helper') {
 1790:         return '';
 1791:     }
 1792:     if (!defined($paramHash->{FILTER_FUNC})) {
 1793:         $paramHash->{FILTER_FUNC} = sub { return 1; };
 1794:     }
 1795:     Apache::lonhelper::files->new();
 1796: }    
 1797: 
 1798: sub start_filechoice {
 1799:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1800: 
 1801:     if ($target ne 'helper') {
 1802:         return '';
 1803:     }
 1804:     $paramHash->{'filechoice'} = Apache::lonxml::get_all_text('/filechoice',
 1805:                                                               $parser);
 1806: }
 1807: 
 1808: sub end_filechoice { return ''; }
 1809: 
 1810: sub start_filefilter {
 1811:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1812: 
 1813:     if ($target ne 'helper') {
 1814:         return '';
 1815:     }
 1816: 
 1817:     my $contents = Apache::lonxml::get_all_text('/filefilter',
 1818:                                                 $parser);
 1819:     $contents = 'sub { my $filename = shift; ' . $contents . '}';
 1820:     $paramHash->{FILTER_FUNC} = eval $contents;
 1821: }
 1822: 
 1823: sub end_filefilter { return ''; }
 1824: 
 1825: sub render {
 1826:     my $self = shift;
 1827:     my $result = '';
 1828:     my $var = $self->{'variable'};
 1829:     
 1830:     my $subdirFunc = eval('sub {' . $self->{'filechoice'} . '}');
 1831:     die 'Error in resource filter code for variable ' . 
 1832:         {'variable'} . ', Perl said:' . $@ if $@;
 1833: 
 1834:     my $subdir = &$subdirFunc();
 1835: 
 1836:     my $filterFunc = $self->{FILTER_FUNC};
 1837:     my $buttons = '';
 1838:     my $type = 'radio';
 1839:     if ($self->{'multichoice'}) {
 1840:         $type = 'checkbox';
 1841:     }
 1842: 
 1843:     if ($self->{'multichoice'}) {
 1844:         $result = <<SCRIPT;
 1845: <script>
 1846:     function checkall(value, checkName) {
 1847: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
 1848:             ele = document.forms.helpform.elements[i];
 1849:             if (ele.name == checkName + '.forminput') {
 1850:                 document.forms.helpform.elements[i].checked=value;
 1851:             }
 1852:         }
 1853:     }
 1854: 
 1855:     function checkallclass(value, className) {
 1856:         for (i=0; i<document.forms.helpform.elements.length; i++) {
 1857:             ele = document.forms.helpform.elements[i];
 1858:             if (ele.type == "$type" && ele.onclick) {
 1859:                 document.forms.helpform.elements[i].checked=value;
 1860:             }
 1861:         }
 1862:     }
 1863: </script>
 1864: SCRIPT
 1865:         $buttons = <<BUTTONS;
 1866: <br /> &nbsp;
 1867: <input type="button" onclick="checkall(true, '$var')" value="Select All Files" />
 1868: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Files" />
 1869: BUTTONS
 1870: 
 1871:         if ($helper->{VARS}->{'construction'}) {
 1872:             $buttons .= <<BUTTONS;
 1873: <input type="button" onclick="checkallclass(true, 'Published')" value="Select All Published" />
 1874: <input type="button" onclick="checkallclass(false, 'Published')" value="Unselect All Published" />
 1875: <br /> &nbsp;
 1876: BUTTONS
 1877:        }
 1878:     }
 1879: 
 1880:     # Get the list of files in this directory.
 1881:     my @fileList;
 1882: 
 1883:     # If the subdirectory is in local CSTR space
 1884:     if ($subdir =~ m|/home/([^/]+)/public_html|) {
 1885:         my $user = $1;
 1886:         my $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 1887:         @fileList = &Apache::lonnet::dirlist($subdir, $domain, $user, '');
 1888:     } else {
 1889:         # local library server resource space
 1890:         @fileList = &Apache::lonnet::dirlist($subdir, $ENV{'user.domain'}, $ENV{'user.name'}, '');
 1891:     }
 1892: 
 1893:     $result .= $buttons;
 1894: 
 1895:     if (defined $self->{ERROR_MSG}) {
 1896:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 1897:     }
 1898: 
 1899:     $result .= '<table border="0" cellpadding="2" cellspacing="0">';
 1900: 
 1901:     # Keeps track if there are no choices, prints appropriate error
 1902:     # if there are none. 
 1903:     my $choices = 0;
 1904:     # Print each legitimate file choice.
 1905:     for my $file (@fileList) {
 1906:         $file = (split(/&/, $file))[0];
 1907:         if ($file eq '.' || $file eq '..') {
 1908:             next;
 1909:         }
 1910:         my $fileName = $subdir .'/'. $file;
 1911:         if (&$filterFunc($file)) {
 1912: 	    my $status;
 1913: 	    my $color;
 1914: 	    if ($helper->{VARS}->{'construction'}) {
 1915: 		($status, $color) = @{fileState($subdir, $file)};
 1916: 	    } else {
 1917: 		$status = '';
 1918: 		$color = '';
 1919: 	    }
 1920: 
 1921:             # Netscape 4 is stupid and there's nowhere to put the
 1922:             # information on the input tag that the file is Published,
 1923:             # Unpublished, etc. In *real* browsers we can just say
 1924:             # "class='Published'" and check the className attribute of
 1925:             # the input tag, but Netscape 4 is too stupid to understand
 1926:             # that attribute, and un-comprehended attributes are not
 1927:             # reflected into the object model. So instead, what I do 
 1928:             # is either have or don't have an "onclick" handler that 
 1929:             # does nothing, give Published files the onclick handler, and
 1930:             # have the checker scripts check for that. Stupid and clumsy,
 1931:             # and only gives us binary "yes/no" information (at least I
 1932:             # couldn't figure out how to reach into the event handler's
 1933:             # actual code to retreive a value), but it works well enough
 1934:             # here.
 1935:         
 1936:             my $onclick = '';
 1937:             if ($status eq 'Published' && $helper->{VARS}->{'construction'}) {
 1938:                 $onclick = 'onclick="a=1" ';
 1939:             }
 1940:             $result .= '<tr><td align="right"' . " bgcolor='$color'>" .
 1941:                 "<input $onclick type='$type' name='" . $var
 1942:             . ".forminput' value='" . HTML::Entities::encode($fileName) .
 1943:                 "'";
 1944:             if (!$self->{'multichoice'} && $choices == 0) {
 1945:                 $result .= ' checked';
 1946:             }
 1947:             $result .= "/></td><td bgcolor='$color'>" . $file .
 1948:                  "</td><td bgcolor='$color'>$status</td></tr>\n";
 1949:             $choices++;
 1950:         }
 1951:     }
 1952: 
 1953:     $result .= "</table>\n";
 1954: 
 1955:     if (!$choices) {
 1956:         $result .= '<font color="#FF0000">There are no files available to select in this directory. Please go back and select another option.</font><br /><br />';
 1957:     }
 1958: 
 1959:     $result .= $buttons;
 1960: 
 1961:     return $result;
 1962: }
 1963: 
 1964: # Determine the state of the file: Published, unpublished, modified.
 1965: # Return the color it should be in and a label as a two-element array
 1966: # reference.
 1967: # Logic lifted from lonpubdir.pm, even though I don't know that it's still
 1968: # the most right thing to do.
 1969: 
 1970: sub fileState {
 1971:     my $constructionSpaceDir = shift;
 1972:     my $file = shift;
 1973:     
 1974:     my $docroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1975:     my $subdirpart = $constructionSpaceDir;
 1976:     $subdirpart =~ s/^\/home\/$ENV{'user.name'}\/public_html//;
 1977:     my $resdir = $docroot . '/res/' . $ENV{'user.domain'} . '/' . $ENV{'user.name'} .
 1978:         $subdirpart;
 1979: 
 1980:     my @constructionSpaceFileStat = stat($constructionSpaceDir . '/' . $file);
 1981:     my @resourceSpaceFileStat = stat($resdir . '/' . $file);
 1982:     if (!@resourceSpaceFileStat) {
 1983:         return ['Unpublished', '#FFCCCC'];
 1984:     }
 1985: 
 1986:     my $constructionSpaceFileModified = $constructionSpaceFileStat[9];
 1987:     my $resourceSpaceFileModified = $resourceSpaceFileStat[9];
 1988:     
 1989:     if ($constructionSpaceFileModified > $resourceSpaceFileModified) {
 1990:         return ['Modified', '#FFFFCC'];
 1991:     }
 1992:     return ['Published', '#CCFFCC'];
 1993: }
 1994: 
 1995: sub postprocess {
 1996:     my $self = shift;
 1997:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
 1998:     if (!$result) {
 1999:         $self->{ERROR_MSG} = 'You must choose at least one file '.
 2000:             'to continue.';
 2001:         return 0;
 2002:     }
 2003: 
 2004:     if ($self->{'multichoice'}) {
 2005:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
 2006:                                         $self->{'variable'});
 2007:     }
 2008:     if (defined($self->{NEXTSTATE})) {
 2009:         $helper->changeState($self->{NEXTSTATE});
 2010:     }
 2011: 
 2012:     return 1;
 2013: }
 2014: 
 2015: 1;
 2016: 
 2017: package Apache::lonhelper::section;
 2018: 
 2019: =pod
 2020: 
 2021: =head2 Element: section
 2022: 
 2023: <section> allows the user to choose one or more sections from the current
 2024: course.
 2025: 
 2026: It takes the standard attributes "variable", "multichoice", and
 2027: "nextstate", meaning what they do for most other elements.
 2028: 
 2029: =cut
 2030: 
 2031: no strict;
 2032: @ISA = ("Apache::lonhelper::choices");
 2033: use strict;
 2034: 
 2035: BEGIN {
 2036:     &Apache::lonhelper::register('Apache::lonhelper::section',
 2037:                                  ('section'));
 2038: }
 2039: 
 2040: sub new {
 2041:     my $ref = Apache::lonhelper::choices->new();
 2042:     bless($ref);
 2043: }
 2044: 
 2045: sub start_section {
 2046:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2047: 
 2048:     if ($target ne 'helper') {
 2049:         return '';
 2050:     }
 2051: 
 2052:     $paramHash->{CHOICES} = [];
 2053: 
 2054:     $paramHash->{'variable'} = $token->[2]{'variable'};
 2055:     $helper->declareVar($paramHash->{'variable'});
 2056:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 2057:     if (defined($token->[2]{'nextstate'})) {
 2058:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
 2059:     }
 2060: 
 2061:     # Populate the CHOICES element
 2062:     my %choices;
 2063: 
 2064:     my $section = Apache::loncoursedata::CL_SECTION();
 2065:     my $classlist = Apache::loncoursedata::get_classlist();
 2066:     foreach (keys %$classlist) {
 2067:         my $sectionName = $classlist->{$_}->[$section];
 2068:         if (!$sectionName) {
 2069:             $choices{"No section assigned"} = "";
 2070:         } else {
 2071:             $choices{$sectionName} = $sectionName;
 2072:         }
 2073:     } 
 2074:    
 2075:     for my $sectionName (sort(keys(%choices))) {
 2076:         
 2077:         push @{$paramHash->{CHOICES}}, [$sectionName, $sectionName];
 2078:     }
 2079: }    
 2080: 
 2081: sub end_section {
 2082:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2083: 
 2084:     if ($target ne 'helper') {
 2085:         return '';
 2086:     }
 2087:     Apache::lonhelper::section->new();
 2088: }    
 2089: 1;
 2090: 
 2091: package Apache::lonhelper::general;
 2092: 
 2093: =pod
 2094: 
 2095: =head2 General-purpose tag: <exec>
 2096: 
 2097: The contents of the exec tag are executed as Perl code, not inside a 
 2098: safe space, so the full range of $ENV and such is available. The code
 2099: will be executed as a subroutine wrapped with the following code:
 2100: 
 2101: "sub { my $helper = shift; my $state = shift;" and
 2102: 
 2103: "}"
 2104: 
 2105: The return value is ignored.
 2106: 
 2107: $helper is the helper object. Feel free to add methods to the helper
 2108: object to support whatever manipulation you may need to do (for instance,
 2109: overriding the form location if the state is the final state; see 
 2110: lonparm.helper for an example).
 2111: 
 2112: $state is the $paramHash that has currently been generated and may
 2113: be manipulated by the code in exec. Note that the $state is not yet
 2114: an actual state B<object>, it is just a hash, so do not expect to
 2115: be able to call methods on it.
 2116: 
 2117: =cut
 2118: 
 2119: BEGIN {
 2120:     &Apache::lonhelper::register('Apache::lonhelper::general',
 2121:                                  'exec', 'condition', 'clause',
 2122:                                  'eval');
 2123: }
 2124: 
 2125: sub start_exec {
 2126:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2127: 
 2128:     if ($target ne 'helper') {
 2129:         return '';
 2130:     }
 2131:     
 2132:     my $code = &Apache::lonxml::get_all_text('/exec', $parser);
 2133:     
 2134:     $code = eval ('sub { my $helper = shift; my $state = shift; ' .
 2135:         $code . "}");
 2136:     die 'Error in <exec>, Perl said: '. $@ if $@;
 2137:     &$code($helper, $paramHash);
 2138: }
 2139: 
 2140: sub end_exec { return ''; }
 2141: 
 2142: =pod
 2143: 
 2144: =head2 General-purpose tag: <condition>
 2145: 
 2146: The <condition> tag allows you to mask out parts of the helper code
 2147: depending on some programatically determined condition. The condition
 2148: tag contains a tag <clause> which contains perl code that when wrapped
 2149: with "sub { my $helper = shift; my $state = shift; " and "}", returns
 2150: a true value if the XML in the condition should be evaluated as a normal
 2151: part of the helper, or false if it should be completely discarded.
 2152: 
 2153: The <clause> tag must be the first sub-tag of the <condition> tag or
 2154: it will not work as expected.
 2155: 
 2156: =cut
 2157: 
 2158: # The condition tag just functions as a marker, it doesn't have
 2159: # to "do" anything. Technically it doesn't even have to be registered
 2160: # with the lonxml code, but I leave this here to be explicit about it.
 2161: sub start_condition { return ''; }
 2162: sub end_condition { return ''; }
 2163: 
 2164: sub start_clause {
 2165:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2166: 
 2167:     if ($target ne 'helper') {
 2168:         return '';
 2169:     }
 2170:     
 2171:     my $clause = Apache::lonxml::get_all_text('/clause', $parser);
 2172:     $clause = eval('sub { my $helper = shift; my $state = shift; '
 2173:         . $clause . '}');
 2174:     die 'Error in clause of condition, Perl said: ' . $@ if $@;
 2175:     if (!&$clause($helper, $paramHash)) {
 2176:         # Discard all text until the /condition.
 2177:         &Apache::lonxml::get_all_text('/condition', $parser);
 2178:     }
 2179: }
 2180: 
 2181: sub end_clause { return ''; }
 2182: 
 2183: =pod
 2184: 
 2185: =head2 General-purpose tag: <eval>
 2186: 
 2187: The <eval> tag will be evaluated as a subroutine call passed in the
 2188: current helper object and state hash as described in <condition> above,
 2189: but is expected to return a string to be printed directly to the
 2190: screen. This is useful for dynamically generating messages. 
 2191: 
 2192: =cut
 2193: 
 2194: # This is basically a type of message.
 2195: # Programmatically setting $paramHash->{NEXTSTATE} would work, though
 2196: # it's probably bad form.
 2197: 
 2198: sub start_eval {
 2199:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2200: 
 2201:     if ($target ne 'helper') {
 2202:         return '';
 2203:     }
 2204:     
 2205:     my $program = Apache::lonxml::get_all_text('/eval', $parser);
 2206:     $program = eval('sub { my $helper = shift; my $state = shift; '
 2207:         . $program . '}');
 2208:     die 'Error in eval code, Perl said: ' . $@ if $@;
 2209:     $paramHash->{MESSAGE_TEXT} = &$program($helper, $paramHash);
 2210: }
 2211: 
 2212: sub end_eval { 
 2213:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2214: 
 2215:     if ($target ne 'helper') {
 2216:         return '';
 2217:     }
 2218: 
 2219:     Apache::lonhelper::message->new();
 2220: }
 2221: 
 2222: 1;
 2223: 
 2224: package Apache::lonhelper::parmwizfinal;
 2225: 
 2226: # This is the final state for the parmwizard. It is not generally useful,
 2227: # so it is not perldoc'ed. It does its own processing.
 2228: # It is represented with <parmwizfinal />, and
 2229: # should later be moved to lonparmset.pm .
 2230: 
 2231: no strict;
 2232: @ISA = ('Apache::lonhelper::element');
 2233: use strict;
 2234: 
 2235: BEGIN {
 2236:     &Apache::lonhelper::register('Apache::lonhelper::parmwizfinal',
 2237:                                  ('parmwizfinal'));
 2238: }
 2239: 
 2240: use Time::localtime;
 2241: 
 2242: sub new {
 2243:     my $ref = Apache::lonhelper::choices->new();
 2244:     bless ($ref);
 2245: }
 2246: 
 2247: sub start_parmwizfinal { return ''; }
 2248: 
 2249: sub end_parmwizfinal {
 2250:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2251: 
 2252:     if ($target ne 'helper') {
 2253:         return '';
 2254:     }
 2255:     Apache::lonhelper::parmwizfinal->new();
 2256: }
 2257: 
 2258: # Renders a form that, when submitted, will form the input to lonparmset.pm
 2259: sub render {
 2260:     my $self = shift;
 2261:     my $vars = $helper->{VARS};
 2262: 
 2263:     # FIXME: Unify my designators with the standard ones
 2264:     my %dateTypeHash = ('open_date' => "Opening Date",
 2265:                         'due_date' => "Due Date",
 2266:                         'answer_date' => "Answer Date");
 2267:     my %parmTypeHash = ('open_date' => "0_opendate",
 2268:                         'due_date' => "0_duedate",
 2269:                         'answer_date' => "0_answerdate");
 2270:     
 2271:     my $result = "<form name='helpform' method='get' action='/adm/parmset'>\n";
 2272:     $result .= '<p>Confirm that this information is correct, then click &quot;Finish Wizard&quot; to complete setting the parameter.<ul>';
 2273:     my $affectedResourceId = "";
 2274:     my $parm_name = $parmTypeHash{$vars->{ACTION_TYPE}};
 2275:     my $level = "";
 2276:     
 2277:     # Print the type of manipulation:
 2278:     $result .= '<li>Setting the <b>' . $dateTypeHash{$vars->{ACTION_TYPE}}
 2279:                . "</b></li>\n";
 2280:     if ($vars->{ACTION_TYPE} eq 'due_date' || 
 2281:         $vars->{ACTION_TYPE} eq 'answer_date') {
 2282:         # for due dates, we default to "date end" type entries
 2283:         $result .= "<input type='hidden' name='recent_date_end' " .
 2284:             "value='" . $vars->{PARM_DATE} . "' />\n";
 2285:         $result .= "<input type='hidden' name='pres_value' " . 
 2286:             "value='" . $vars->{PARM_DATE} . "' />\n";
 2287:         $result .= "<input type='hidden' name='pres_type' " .
 2288:             "value='date_end' />\n";
 2289:     } elsif ($vars->{ACTION_TYPE} eq 'open_date') {
 2290:         $result .= "<input type='hidden' name='recent_date_start' ".
 2291:             "value='" . $vars->{PARM_DATE} . "' />\n";
 2292:         $result .= "<input type='hidden' name='pres_value' " .
 2293:             "value='" . $vars->{PARM_DATE} . "' />\n";
 2294:         $result .= "<input type='hidden' name='pres_type' " .
 2295:             "value='date_start' />\n";
 2296:     } 
 2297:     
 2298:     # Print the granularity, depending on the action
 2299:     if ($vars->{GRANULARITY} eq 'whole_course') {
 2300:         $result .= '<li>for <b>all resources in the course</b></li>';
 2301:         $level = 9; # general course, see lonparmset.pm perldoc
 2302:         $affectedResourceId = "0.0";
 2303:     } elsif ($vars->{GRANULARITY} eq 'map') {
 2304:         my $navmap = Apache::lonnavmaps::navmap->new(
 2305:                            $ENV{"request.course.fn"}.".db",
 2306:                            $ENV{"request.course.fn"}."_parms.db", 0, 0);
 2307:         my $res = $navmap->getById($vars->{RESOURCE_ID});
 2308:         my $title = $res->compTitle();
 2309:         $navmap->untieHashes();
 2310:         $result .= "<li>for the map named <b>$title</b></li>";
 2311:         $level = 8;
 2312:         $affectedResourceId = $vars->{RESOURCE_ID};
 2313:     } else {
 2314:         my $navmap = Apache::lonnavmaps::navmap->new(
 2315:                            $ENV{"request.course.fn"}.".db",
 2316:                            $ENV{"request.course.fn"}."_parms.db", 0, 0);
 2317:         my $res = $navmap->getById($vars->{RESOURCE_ID});
 2318:         my $title = $res->compTitle();
 2319:         $navmap->untieHashes();
 2320:         $result .= "<li>for the resource named <b>$title</b></li>";
 2321:         $level = 7;
 2322:         $affectedResourceId = $vars->{RESOURCE_ID};
 2323:     }
 2324: 
 2325:     # Print targets
 2326:     if ($vars->{TARGETS} eq 'course') {
 2327:         $result .= '<li>for <b>all students in course</b></li>';
 2328:     } elsif ($vars->{TARGETS} eq 'section') {
 2329:         my $section = $vars->{SECTION_NAME};
 2330:         $result .= "<li>for section <b>$section</b></li>";
 2331:         $level -= 3;
 2332:         $result .= "<input type='hidden' name='csec' value='" .
 2333:             HTML::Entities::encode($section) . "' />\n";
 2334:     } else {
 2335:         # FIXME: This is probably wasteful! Store the name!
 2336:         my $classlist = Apache::loncoursedata::get_classlist();
 2337:         my $name = $classlist->{$vars->{USER_NAME}}->[6];
 2338:         $result .= "<li>for <b>$name</b></li>";
 2339:         $level -= 6;
 2340:         my ($uname, $udom) = split /:/, $vars->{USER_NAME};
 2341:         $result .= "<input type='hidden' name='uname' value='".
 2342:             HTML::Entities::encode($uname) . "' />\n";
 2343:         $result .= "<input type='hidden' name='udom' value='".
 2344:             HTML::Entities::encode($udom) . "' />\n";
 2345:     }
 2346: 
 2347:     # Print value
 2348:     $result .= "<li>to <b>" . ctime($vars->{PARM_DATE}) . "</b> (" .
 2349:         Apache::lonnavmaps::timeToHumanString($vars->{PARM_DATE}) 
 2350:         . ")</li>\n";
 2351: 
 2352:     # print pres_marker
 2353:     $result .= "\n<input type='hidden' name='pres_marker'" .
 2354:         " value='$affectedResourceId&$parm_name&$level' />\n";
 2355: 
 2356:     $result .= "<br /><br /><center><input type='submit' value='Finish Helper' /></center></form>\n";
 2357: 
 2358:     return $result;
 2359: }
 2360:     
 2361: sub overrideForm {
 2362:     return 1;
 2363: }
 2364: 
 2365: 1;
 2366: 
 2367: __END__
 2368: 

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