File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.84: download - view: text, annotated - select for diffs
Tue Aug 3 18:41:20 2004 UTC (19 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: version_1_1_99_4, HEAD
- removing log spew

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

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