Annotation of loncom/interface/lonhelper.pm, revision 1.141

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

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