File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.154: download - view: text, annotated - select for diffs
Tue May 30 21:54:22 2006 UTC (18 years ago) by albertel
Branches: MAIN
CVS tags: HEAD
- use was not added to the subpackage

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

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