File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.166.2.2: download - view: text, annotated - select for diffs
Sun Dec 21 16:24:49 2008 UTC (15 years, 5 months ago) by raeburn
Branches: version_2_8_X
CVS tags: version_2_8_2, version_2_8_1, version_2_8_0, version_2_7_99_1, version_2_7_99_0, GCI_1
Diff to branchpoint 1.166: preferred, unified
- Backport 1.169.

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

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