File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.151: download - view: text, annotated - select for diffs
Thu May 18 01:08:51 2006 UTC (18 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
&coursegroups() and &get_group_settings() moved to longroup.pm, which contains general utility functions for asking about groups.  Also contains &group_changes() which is used to add/drop group memberships as a result of role changes, as determined by group settings for auto-add and auto-drop. 'none' and 'all' are now reserved words which may not be used as section or group names, so they can be used instead of _all and _none  when specifying auto-add and auto-drop settings for all sections or no section roles.

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

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