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

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

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