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

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

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