File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.172: download - view: text, annotated - select for diffs
Mon May 11 16:51:27 2009 UTC (15 years ago) by bisitz
Branches: MAIN
CVS tags: version_2_9_X, version_2_9_1, version_2_9_0, version_2_8_99_1, version_2_8_99_0, HEAD, GCI_2, BZ5434-fox
XHTML: Attributes in lower-case only (<form method="post" ...)

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

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