File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.73: download - view: text, annotated - select for diffs
Wed Apr 21 19:03:02 2004 UTC (20 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- I think this might be more translatable

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

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