File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.106: download - view: text, annotated - select for diffs
Thu Jul 7 04:16:01 2005 UTC (18 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- final confirmation screen in helper wasn't showing the full name of the user

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

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