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

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

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