File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.129: download - view: text, annotated - select for diffs
Tue Jan 17 18:39:50 2006 UTC (18 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- use style file link didn't actually work (BUG#4575)

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

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