File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.174: download - view: text, annotated - select for diffs
Fri Jun 12 15:31:30 2009 UTC (15 years ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Added breadcrumbs to helper.
This currently covers only basic call and general "Helper" crumb.

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

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