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

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

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