File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.69: download - view: text, annotated - select for diffs
Tue Apr 20 15:08:26 2004 UTC (20 years, 1 month ago) by sakharuk
Branches: MAIN
CVS tags: HEAD
Some localization is done.

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

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