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

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

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