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

1.1       bowersj2    1: # The LearningOnline Network with CAPA
                      2: # .helper XML handler to implement the LON-CAPA helper
                      3: #
1.14      bowersj2    4: # $Id: lonhelper.pm,v 1.13 2003/04/30 15:18:36 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.13      bowersj2  196: # For debugging purposes, one can send a second parameter into this
                    197: # function, the 'uri' of the helper you wish to have rendered, and
                    198: # call this from other handlers.
1.2       bowersj2  199: sub handler {
1.3       bowersj2  200:     my $r = shift;
1.13      bowersj2  201:     my $uri = shift;
                    202:     if (!defined($uri)) { $uri = $r->uri(); }
                    203:     $ENV{'request.uri'} = $uri;
                    204:     my $filename = '/home/httpd/html' . $uri;
1.2       bowersj2  205:     my $fh = Apache::File->new($filename);
                    206:     my $file;
1.3       bowersj2  207:     read $fh, $file, 100000000;
                    208: 
                    209:     # Send header, don't cache this page
                    210:     if ($r->header_only) {
                    211:         if ($ENV{'browser.mathml'}) {
                    212:             $r->content_type('text/xml');
                    213:         } else {
                    214:             $r->content_type('text/html');
                    215:         }
                    216:         $r->send_http_header;
                    217:         return OK;
                    218:     }
                    219:     if ($ENV{'browser.mathml'}) {
                    220:         $r->content_type('text/xml');
                    221:     } else {
                    222:         $r->content_type('text/html');
                    223:     }
                    224:     $r->send_http_header;
                    225:     $r->rflush();
1.2       bowersj2  226: 
1.3       bowersj2  227:     # Discard result, we just want the objects that get created by the
                    228:     # xml parsing
                    229:     &Apache::lonxml::xmlparse($r, 'helper', $file);
1.2       bowersj2  230: 
1.13      bowersj2  231:     $helper->process();
                    232: 
1.3       bowersj2  233:     $r->print($helper->display());
1.7       bowersj2  234:    return OK;
1.2       bowersj2  235: }
                    236: 
1.13      bowersj2  237: sub registerHelperTags {
                    238:     for my $tagList (@helperTags) {
                    239:         Apache::lonxml::register($tagList->[0], $tagList->[1]);
                    240:     }
                    241: }
                    242: 
                    243: sub unregisterHelperTags {
                    244:     for my $tagList (@helperTags) {
                    245:         Apache::lonxml::deregister($tagList->[0], $tagList->[1]);
                    246:     }
                    247: }
                    248: 
1.2       bowersj2  249: sub start_helper {
                    250:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    251: 
                    252:     if ($target ne 'helper') {
                    253:         return '';
                    254:     }
1.7       bowersj2  255: 
1.13      bowersj2  256:     registerHelperTags();
                    257: 
                    258:     Apache::lonhelper::helper->new($token->[2]{'title'});
1.4       bowersj2  259:     return '';
1.2       bowersj2  260: }
                    261: 
                    262: sub end_helper {
                    263:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    264:     
1.3       bowersj2  265:     if ($target ne 'helper') {
                    266:         return '';
                    267:     }
1.7       bowersj2  268: 
1.13      bowersj2  269:     unregisterHelperTags();
1.7       bowersj2  270: 
1.4       bowersj2  271:     return '';
1.2       bowersj2  272: }
1.1       bowersj2  273: 
1.3       bowersj2  274: sub start_state {
                    275:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    276: 
                    277:     if ($target ne 'helper') {
                    278:         return '';
                    279:     }
                    280: 
1.13      bowersj2  281:     Apache::lonhelper::state->new($token->[2]{'name'},
                    282:                                   $token->[2]{'title'});
1.3       bowersj2  283:     return '';
                    284: }
                    285: 
1.13      bowersj2  286: # Use this to get the param hash from other files.
                    287: sub getParamHash {
                    288:     return $paramHash;
                    289: }
                    290: 
                    291: # Use this to get the helper, if implementing elements in other files
                    292: # (like lonprintout.pm)
                    293: sub getHelper {
                    294:     return $helper;
                    295: }
                    296: 
1.3       bowersj2  297: # don't need this, so ignore it
                    298: sub end_state {
                    299:     return '';
                    300: }
                    301: 
1.1       bowersj2  302: 1;
                    303: 
1.3       bowersj2  304: package Apache::lonhelper::helper;
                    305: 
                    306: use Digest::MD5 qw(md5_hex);
                    307: use HTML::Entities;
                    308: use Apache::loncommon;
                    309: use Apache::File;
                    310: 
                    311: sub new {
                    312:     my $proto = shift;
                    313:     my $class = ref($proto) || $proto;
                    314:     my $self = {};
                    315: 
                    316:     $self->{TITLE} = shift;
                    317:     
                    318:     # If there is a state from the previous form, use that. If there is no
                    319:     # state, use the start state parameter.
                    320:     if (defined $ENV{"form.CURRENT_STATE"})
                    321:     {
                    322: 	$self->{STATE} = $ENV{"form.CURRENT_STATE"};
                    323:     }
                    324:     else
                    325:     {
                    326: 	$self->{STATE} = "START";
                    327:     }
                    328: 
1.14      bowersj2  329:     Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
                    330: 
1.3       bowersj2  331:     $self->{TOKEN} = $ENV{'form.TOKEN'};
                    332:     # If a token was passed, we load that in. Otherwise, we need to create a 
                    333:     # new storage file
                    334:     # Tried to use standard Tie'd hashes, but you can't seem to take a 
                    335:     # reference to a tied hash and write to it. I'd call that a wart.
                    336:     if ($self->{TOKEN}) {
                    337:         # Validate the token before trusting it
                    338:         if ($self->{TOKEN} !~ /^[a-f0-9]{32}$/) {
                    339:             # Not legit. Return nothing and let all hell break loose.
                    340:             # User shouldn't be doing that!
                    341:             return undef;
                    342:         }
                    343: 
                    344:         # Get the hash.
                    345:         $self->{FILENAME} = $Apache::lonnet::tmpdir . md5_hex($self->{TOKEN}); # Note the token is not the literal file
                    346:         
                    347:         my $file = Apache::File->new($self->{FILENAME});
                    348:         my $contents = <$file>;
1.5       bowersj2  349: 
                    350:         # Now load in the contents
                    351:         for my $value (split (/&/, $contents)) {
                    352:             my ($name, $value) = split(/=/, $value);
                    353:             $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
                    354:             $self->{VARS}->{$name} = $value;
                    355:         }
                    356: 
1.3       bowersj2  357:         $file->close();
                    358:     } else {
                    359:         # Only valid if we're just starting.
                    360:         if ($self->{STATE} ne 'START') {
                    361:             return undef;
                    362:         }
                    363:         # Must create the storage
                    364:         $self->{TOKEN} = md5_hex($ENV{'user.name'} . $ENV{'user.domain'} .
                    365:                                  time() . rand());
                    366:         $self->{FILENAME} = $Apache::lonnet::tmpdir . md5_hex($self->{TOKEN});
                    367:     }
                    368: 
                    369:     # OK, we now have our persistent storage.
                    370: 
                    371:     if (defined $ENV{"form.RETURN_PAGE"})
                    372:     {
                    373: 	$self->{RETURN_PAGE} = $ENV{"form.RETURN_PAGE"};
                    374:     }
                    375:     else
                    376:     {
                    377: 	$self->{RETURN_PAGE} = $ENV{REFERER};
                    378:     }
                    379: 
                    380:     $self->{STATES} = {};
                    381:     $self->{DONE} = 0;
                    382: 
1.9       bowersj2  383:     # Used by various helpers for various things; see lonparm.helper
                    384:     # for an example.
                    385:     $self->{DATA} = {};
                    386: 
1.13      bowersj2  387:     $helper = $self;
                    388: 
                    389:     # Establish the $paramHash
                    390:     $paramHash = {};
                    391: 
1.3       bowersj2  392:     bless($self, $class);
                    393:     return $self;
                    394: }
                    395: 
                    396: # Private function; returns a string to construct the hidden fields
                    397: # necessary to have the helper track state.
                    398: sub _saveVars {
                    399:     my $self = shift;
                    400:     my $result = "";
                    401:     $result .= '<input type="hidden" name="CURRENT_STATE" value="' .
                    402:         HTML::Entities::encode($self->{STATE}) . "\" />\n";
                    403:     $result .= '<input type="hidden" name="TOKEN" value="' .
                    404:         $self->{TOKEN} . "\" />\n";
                    405:     $result .= '<input type="hidden" name="RETURN_PAGE" value="' .
                    406:         HTML::Entities::encode($self->{RETURN_PAGE}) . "\" />\n";
                    407: 
                    408:     return $result;
                    409: }
                    410: 
                    411: # Private function: Create the querystring-like representation of the stored
                    412: # data to write to disk.
                    413: sub _varsInFile {
                    414:     my $self = shift;
                    415:     my @vars = ();
                    416:     for my $key (keys %{$self->{VARS}}) {
                    417:         push @vars, &Apache::lonnet::escape($key) . '=' .
                    418:             &Apache::lonnet::escape($self->{VARS}->{$key});
                    419:     }
                    420:     return join ('&', @vars);
                    421: }
                    422: 
1.5       bowersj2  423: # Use this to declare variables.
                    424: # FIXME: Document this
                    425: sub declareVar {
                    426:     my $self = shift;
                    427:     my $var = shift;
                    428: 
                    429:     if (!defined($self->{VARS}->{$var})) {
                    430:         $self->{VARS}->{$var} = '';
                    431:     }
                    432: 
                    433:     my $envname = 'form.' . $var . '.forminput';
                    434:     if (defined($ENV{$envname})) {
                    435:         $self->{VARS}->{$var} = $ENV{$envname};
                    436:     }
                    437: }
                    438: 
1.3       bowersj2  439: sub changeState {
                    440:     my $self = shift;
                    441:     $self->{STATE} = shift;
                    442: }
                    443: 
                    444: sub registerState {
                    445:     my $self = shift;
                    446:     my $state = shift;
                    447: 
                    448:     my $stateName = $state->name();
                    449:     $self->{STATES}{$stateName} = $state;
                    450: }
                    451: 
1.13      bowersj2  452: sub process {
1.3       bowersj2  453:     my $self = shift;
                    454: 
                    455:     # Phase 1: Post processing for state of previous screen (which is actually
                    456:     # the "current state" in terms of the helper variables), if it wasn't the 
                    457:     # beginning state.
                    458:     if ($self->{STATE} ne "START" || $ENV{"form.SUBMIT"} eq "Next ->") {
                    459: 	my $prevState = $self->{STATES}{$self->{STATE}};
1.13      bowersj2  460:         $prevState->postprocess();
1.3       bowersj2  461:     }
                    462:     
                    463:     # Note, to handle errors in a state's input that a user must correct,
                    464:     # do not transition in the postprocess, and force the user to correct
                    465:     # the error.
                    466: 
                    467:     # Phase 2: Preprocess current state
                    468:     my $startState = $self->{STATE};
1.17      bowersj2  469:     my $state = $self->{STATES}->{$startState};
1.3       bowersj2  470:     
1.13      bowersj2  471:     # For debugging, print something here to determine if you're going
                    472:     # to an undefined state.
1.3       bowersj2  473:     if (!defined($state)) {
1.13      bowersj2  474:         return;
1.3       bowersj2  475:     }
                    476:     $state->preprocess();
                    477: 
                    478:     # Phase 3: While the current state is different from the previous state,
                    479:     # keep processing.
1.17      bowersj2  480:     while ( $startState ne $self->{STATE} && 
                    481:             defined($self->{STATES}->{$self->{STATE}}) )
1.3       bowersj2  482:     {
                    483: 	$startState = $self->{STATE};
1.17      bowersj2  484: 	$state = $self->{STATES}->{$startState};
1.3       bowersj2  485: 	$state->preprocess();
                    486:     }
                    487: 
1.13      bowersj2  488:     return;
                    489: } 
                    490: 
                    491: # 1: Do the post processing for the previous state.
                    492: # 2: Do the preprocessing for the current state.
                    493: # 3: Check to see if state changed, if so, postprocess current and move to next.
                    494: #    Repeat until state stays stable.
                    495: # 4: Render the current state to the screen as an HTML page.
                    496: sub display {
                    497:     my $self = shift;
                    498: 
                    499:     my $state = $self->{STATES}{$self->{STATE}};
                    500: 
                    501:     my $result = "";
                    502: 
1.17      bowersj2  503:     if (!defined($state)) {
                    504:         $result = "<font color='#ff0000'>Error: state '$state' not defined!</font>";
                    505:         return $result;
                    506:     }
                    507: 
1.3       bowersj2  508:     # Phase 4: Display.
                    509:     my $stateTitle = $state->title();
                    510:     my $bodytag = &Apache::loncommon::bodytag("$self->{TITLE}",'','');
                    511: 
                    512:     $result .= <<HEADER;
                    513: <html>
                    514:     <head>
                    515:         <title>LON-CAPA Helper: $self->{TITLE}</title>
                    516:     </head>
                    517:     $bodytag
                    518: HEADER
1.14      bowersj2  519:     if (!$state->overrideForm()) { $result.="<form name='helpform' method='GET'>"; }
1.3       bowersj2  520:     $result .= <<HEADER;
                    521:         <table border="0"><tr><td>
                    522:         <h2><i>$stateTitle</i></h2>
                    523: HEADER
                    524: 
                    525:     if (!$state->overrideForm()) {
                    526:         $result .= $self->_saveVars();
                    527:     }
                    528:     $result .= $state->render() . "<p>&nbsp;</p>";
                    529: 
                    530:     if (!$state->overrideForm()) {
                    531:         $result .= '<center>';
                    532:         if ($self->{STATE} ne $self->{START_STATE}) {
                    533:             #$result .= '<input name="SUBMIT" type="submit" value="&lt;- Previous" />&nbsp;&nbsp;';
                    534:         }
                    535:         if ($self->{DONE}) {
                    536:             my $returnPage = $self->{RETURN_PAGE};
                    537:             $result .= "<a href=\"$returnPage\">End Helper</a>";
                    538:         }
                    539:         else {
                    540:             $result .= '<input name="back" type="button" ';
                    541:             $result .= 'value="&lt;- Previous" onclick="history.go(-1)" /> ';
                    542:             $result .= '<input name="SUBMIT" type="submit" value="Next -&gt;" />';
                    543:         }
                    544:         $result .= "</center>\n";
                    545:     }
                    546: 
1.13      bowersj2  547:     #foreach my $key (keys %{$self->{VARS}}) {
                    548:     #    $result .= "|$key| -> " . $self->{VARS}->{$key} . "<br />";
                    549:     #}
1.5       bowersj2  550: 
1.3       bowersj2  551:     $result .= <<FOOTER;
                    552:               </td>
                    553:             </tr>
                    554:           </table>
                    555:         </form>
                    556:     </body>
                    557: </html>
                    558: FOOTER
                    559: 
                    560:     # Handle writing out the vars to the file
                    561:     my $file = Apache::File->new('>'.$self->{FILENAME});
                    562:     print $file $self->_varsInFile();
                    563: 
                    564:     return $result;
                    565: }
                    566: 
                    567: 1;
                    568: 
                    569: package Apache::lonhelper::state;
                    570: 
                    571: # States bundle things together and are responsible for compositing the
1.4       bowersj2  572: # various elements together. It is not generally necessary for users to
                    573: # use the state object directly, so it is not perldoc'ed.
                    574: 
                    575: # Basically, all the states do is pass calls to the elements and aggregate
                    576: # the results.
1.3       bowersj2  577: 
                    578: sub new {
                    579:     my $proto = shift;
                    580:     my $class = ref($proto) || $proto;
                    581:     my $self = {};
                    582: 
                    583:     $self->{NAME} = shift;
                    584:     $self->{TITLE} = shift;
                    585:     $self->{ELEMENTS} = [];
                    586: 
                    587:     bless($self, $class);
                    588: 
                    589:     $helper->registerState($self);
                    590: 
1.13      bowersj2  591:     $state = $self;
                    592: 
1.3       bowersj2  593:     return $self;
                    594: }
                    595: 
                    596: sub name {
                    597:     my $self = shift;
                    598:     return $self->{NAME};
                    599: }
                    600: 
                    601: sub title {
                    602:     my $self = shift;
                    603:     return $self->{TITLE};
                    604: }
                    605: 
1.4       bowersj2  606: sub preprocess {
                    607:     my $self = shift;
                    608:     for my $element (@{$self->{ELEMENTS}}) {
                    609:         $element->preprocess();
                    610:     }
                    611: }
                    612: 
1.6       bowersj2  613: # FIXME: Document that all postprocesses must return a true value or
                    614: # the state transition will be overridden
1.4       bowersj2  615: sub postprocess {
                    616:     my $self = shift;
1.6       bowersj2  617: 
                    618:     # Save the state so we can roll it back if we need to.
                    619:     my $originalState = $helper->{STATE};
                    620:     my $everythingSuccessful = 1;
                    621: 
1.4       bowersj2  622:     for my $element (@{$self->{ELEMENTS}}) {
1.6       bowersj2  623:         my $result = $element->postprocess();
                    624:         if (!$result) { $everythingSuccessful = 0; }
                    625:     }
                    626: 
                    627:     # If not all the postprocesses were successful, override
                    628:     # any state transitions that may have occurred. It is the
                    629:     # responsibility of the states to make sure they have 
                    630:     # error handling in that case.
                    631:     if (!$everythingSuccessful) {
                    632:         $helper->{STATE} = $originalState;
1.4       bowersj2  633:     }
                    634: }
                    635: 
1.13      bowersj2  636: # Override the form if any element wants to.
                    637: # two elements overriding the form will make a mess, but that should
                    638: # be considered helper author error ;-)
1.4       bowersj2  639: sub overrideForm {
1.13      bowersj2  640:     my $self = shift;
                    641:     for my $element (@{$self->{ELEMENTS}}) {
                    642:         if ($element->overrideForm()) {
                    643:             return 1;
                    644:         }
                    645:     }
1.4       bowersj2  646:     return 0;
                    647: }
                    648: 
                    649: sub addElement {
                    650:     my $self = shift;
                    651:     my $element = shift;
                    652:     
                    653:     push @{$self->{ELEMENTS}}, $element;
                    654: }
                    655: 
                    656: sub render {
                    657:     my $self = shift;
                    658:     my @results = ();
                    659: 
                    660:     for my $element (@{$self->{ELEMENTS}}) {
                    661:         push @results, $element->render();
                    662:     }
                    663:     return join("\n", @results);
                    664: }
                    665: 
                    666: 1;
                    667: 
                    668: package Apache::lonhelper::element;
                    669: # Support code for elements
                    670: 
                    671: =pod
                    672: 
                    673: =head2 Element Base Class
                    674: 
                    675: The Apache::lonhelper::element base class provides support methods for
                    676: the elements to use, such as a multiple value processer.
                    677: 
                    678: B<Methods>:
                    679: 
                    680: =over 4
                    681: 
                    682: =item * process_multiple_choices(formName, varName): Process the form 
                    683: element named "formName" and place the selected items into the helper 
                    684: variable named varName. This is for things like checkboxes or 
                    685: multiple-selection listboxes where the user can select more then 
                    686: one entry. The selected entries are delimited by triple pipes in 
1.5       bowersj2  687: the helper variables, like this:  
                    688: 
                    689:  CHOICE_1|||CHOICE_2|||CHOICE_3
1.4       bowersj2  690: 
                    691: =back
                    692: 
                    693: =cut
                    694: 
1.5       bowersj2  695: BEGIN {
1.7       bowersj2  696:     &Apache::lonhelper::register('Apache::lonhelper::element',
                    697:                                  ('nextstate'));
1.5       bowersj2  698: }
                    699: 
1.4       bowersj2  700: # Because we use the param hash, this is often a sufficent
                    701: # constructor
                    702: sub new {
                    703:     my $proto = shift;
                    704:     my $class = ref($proto) || $proto;
                    705:     my $self = $paramHash;
                    706:     bless($self, $class);
                    707: 
                    708:     $self->{PARAMS} = $paramHash;
                    709:     $self->{STATE} = $state;
                    710:     $state->addElement($self);
                    711:     
                    712:     # Ensure param hash is not reused
                    713:     $paramHash = {};
                    714: 
                    715:     return $self;
                    716: }   
                    717: 
1.5       bowersj2  718: sub start_nextstate {
                    719:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    720: 
                    721:     if ($target ne 'helper') {
                    722:         return '';
                    723:     }
                    724:     
                    725:     $paramHash->{NEXTSTATE} = &Apache::lonxml::get_all_text('/nextstate',
                    726:                                                              $parser);
                    727:     return '';
                    728: }
                    729: 
                    730: sub end_nextstate { return ''; }
                    731: 
1.4       bowersj2  732: sub preprocess {
                    733:     return 1;
                    734: }
                    735: 
                    736: sub postprocess {
                    737:     return 1;
                    738: }
                    739: 
                    740: sub render {
                    741:     return '';
                    742: }
                    743: 
1.13      bowersj2  744: sub overrideForm {
                    745:     return 0;
                    746: }
                    747: 
1.3       bowersj2  748: sub process_multiple_choices {
                    749:     my $self = shift;
                    750:     my $formname = shift;
                    751:     my $var = shift;
                    752: 
1.14      bowersj2  753:     # Must extract values from data directly, as there
                    754:     # may be more then one.
                    755:     my @values;
                    756:     for my $formparam (split (/&/, $ENV{QUERY_STRING})) {
                    757:         my ($name, $value) = split(/=/, $formparam);
                    758:         if ($name ne $formname) {
                    759:             next;
1.3       bowersj2  760:         }
1.14      bowersj2  761:         $value =~ tr/+/ /;
                    762:         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
                    763:         push @values, $value;
1.3       bowersj2  764:     }
1.14      bowersj2  765:     $helper->{VARS}->{$var} = join('|||', @values);
1.3       bowersj2  766:     
                    767:     return;
                    768: }
                    769: 
1.4       bowersj2  770: 1;
                    771: 
                    772: package Apache::lonhelper::message;
                    773: 
                    774: =pod
                    775: 
                    776: =head2 Element: message
                    777: 
                    778: Message elements display the contents of their <message_text> tags, and
1.5       bowersj2  779: transition directly to the state in the <nextstate> tag. Example:
1.4       bowersj2  780: 
                    781:  <message>
1.5       bowersj2  782:    <nextstate>GET_NAME</nextstate>
1.4       bowersj2  783:    <message_text>This is the <b>message</b> the user will see, 
                    784:                  <i>HTML allowed</i>.</message_text>
                    785:    </message>
                    786: 
1.5       bowersj2  787: This will display the HTML message and transition to the <nextstate> if
1.7       bowersj2  788: given. The HTML will be directly inserted into the helper, so if you don't
1.4       bowersj2  789: want text to run together, you'll need to manually wrap the <message_text>
                    790: in <p> tags, or whatever is appropriate for your HTML.
                    791: 
1.5       bowersj2  792: Message tags do not add in whitespace, so if you want it, you'll need to add
                    793: it into states. This is done so you can inline some elements, such as 
                    794: the <date> element, right between two messages, giving the appearence that 
                    795: the <date> element appears inline. (Note the elements can not be embedded
                    796: within each other.)
                    797: 
1.4       bowersj2  798: This is also a good template for creating your own new states, as it has
                    799: very little code beyond the state template.
                    800: 
                    801: =cut
                    802: 
                    803: no strict;
                    804: @ISA = ("Apache::lonhelper::element");
                    805: use strict;
                    806: 
                    807: BEGIN {
1.7       bowersj2  808:     &Apache::lonhelper::register('Apache::lonhelper::message',
1.10      bowersj2  809:                               ('message'));
1.3       bowersj2  810: }
                    811: 
1.5       bowersj2  812: sub new {
                    813:     my $ref = Apache::lonhelper::element->new();
                    814:     bless($ref);
                    815: }
1.4       bowersj2  816: 
                    817: # CONSTRUCTION: Construct the message element from the XML
                    818: sub start_message {
                    819:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    820: 
                    821:     if ($target ne 'helper') {
                    822:         return '';
                    823:     }
1.10      bowersj2  824: 
                    825:     $paramHash->{MESSAGE_TEXT} = &Apache::lonxml::get_all_text('/message',
                    826:                                                                $parser);
                    827: 
                    828:     if (defined($token->[2]{'nextstate'})) {
                    829:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
                    830:     }
1.4       bowersj2  831:     return '';
1.3       bowersj2  832: }
                    833: 
1.10      bowersj2  834: sub end_message {
1.4       bowersj2  835:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    836: 
                    837:     if ($target ne 'helper') {
                    838:         return '';
                    839:     }
1.10      bowersj2  840:     Apache::lonhelper::message->new();
                    841:     return '';
1.5       bowersj2  842: }
                    843: 
                    844: sub render {
                    845:     my $self = shift;
                    846: 
                    847:     return $self->{MESSAGE_TEXT};
                    848: }
                    849: # If a NEXTSTATE was given, switch to it
                    850: sub postprocess {
                    851:     my $self = shift;
                    852:     if (defined($self->{NEXTSTATE})) {
                    853:         $helper->changeState($self->{NEXTSTATE});
                    854:     }
1.6       bowersj2  855: 
                    856:     return 1;
1.5       bowersj2  857: }
                    858: 1;
                    859: 
                    860: package Apache::lonhelper::choices;
                    861: 
                    862: =pod
                    863: 
                    864: =head2 Element: choices
                    865: 
                    866: Choice states provide a single choice to the user as a text selection box.
                    867: A "choice" is two pieces of text, one which will be displayed to the user
                    868: (the "human" value), and one which will be passed back to the program
                    869: (the "computer" value). For instance, a human may choose from a list of
                    870: resources on disk by title, while your program wants the file name.
                    871: 
                    872: <choices> takes an attribute "variable" to control which helper variable
                    873: the result is stored in.
                    874: 
                    875: <choices> takes an attribute "multichoice" which, if set to a true
                    876: value, will allow the user to select multiple choices.
                    877: 
                    878: B<SUB-TAGS>
                    879: 
                    880: <choices> can have the following subtags:
                    881: 
                    882: =over 4
                    883: 
                    884: =item * <nextstate>state_name</nextstate>: If given, this will cause the
                    885:       choice element to transition to the given state after executing. If
                    886:       this is used, do not pass nextstates to the <choice> tag.
                    887: 
                    888: =item * <choice />: If the choices are static,
                    889:       this element will allow you to specify them. Each choice
                    890:       contains  attribute, "computer", as described above. The
                    891:       content of the tag will be used as the human label.
                    892:       For example,  
                    893:       <choice computer='234-12-7312'>Bobby McDormik</choice>.
                    894: 
1.13      bowersj2  895:       <choice> can take a parameter "eval", which if set to
                    896:       a true value, will cause the contents of the tag to be
                    897:       evaluated as it would be in an <eval> tag; see <eval> tag
                    898:       below.
                    899: 
1.5       bowersj2  900: <choice> may optionally contain a 'nextstate' attribute, which
                    901: will be the state transisitoned to if the choice is made, if
                    902: the choice is not multichoice.
                    903: 
                    904: =back
                    905: 
                    906: To create the choices programmatically, either wrap the choices in 
                    907: <condition> tags (prefered), or use an <exec> block inside the <choice>
                    908: tag. Store the choices in $state->{CHOICES}, which is a list of list
                    909: references, where each list has three strings. The first is the human
                    910: name, the second is the computer name. and the third is the option
                    911: next state. For example:
                    912: 
                    913:  <exec>
                    914:     for (my $i = 65; $i < 65 + 26; $i++) {
                    915:         push @{$state->{CHOICES}}, [chr($i), $i, 'next'];
                    916:     }
                    917:  </exec>
                    918: 
                    919: This will allow the user to select from the letters A-Z (in ASCII), while
                    920: passing the ASCII value back into the helper variables, and the state
                    921: will in all cases transition to 'next'.
                    922: 
                    923: You can mix and match methods of creating choices, as long as you always 
                    924: "push" onto the choice list, rather then wiping it out. (You can even 
                    925: remove choices programmatically, but that would probably be bad form.)
                    926: 
                    927: =cut
                    928: 
                    929: no strict;
                    930: @ISA = ("Apache::lonhelper::element");
                    931: use strict;
                    932: 
                    933: BEGIN {
1.7       bowersj2  934:     &Apache::lonhelper::register('Apache::lonhelper::choices',
1.5       bowersj2  935:                               ('choice', 'choices'));
                    936: }
                    937: 
                    938: sub new {
                    939:     my $ref = Apache::lonhelper::element->new();
                    940:     bless($ref);
                    941: }
                    942: 
                    943: # CONSTRUCTION: Construct the message element from the XML
                    944: sub start_choices {
                    945:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    946: 
                    947:     if ($target ne 'helper') {
                    948:         return '';
                    949:     }
                    950: 
                    951:     # Need to initialize the choices list, so everything can assume it exists
                    952:     $paramHash->{'variable'} = $token->[2]{'variable'};
                    953:     $helper->declareVar($paramHash->{'variable'});
                    954:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
                    955:     $paramHash->{CHOICES} = [];
                    956:     return '';
                    957: }
                    958: 
                    959: sub end_choices {
                    960:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    961: 
                    962:     if ($target ne 'helper') {
                    963:         return '';
                    964:     }
                    965:     Apache::lonhelper::choices->new();
                    966:     return '';
                    967: }
                    968: 
                    969: sub start_choice {
                    970:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    971: 
                    972:     if ($target ne 'helper') {
                    973:         return '';
                    974:     }
                    975: 
                    976:     my $computer = $token->[2]{'computer'};
                    977:     my $human = &Apache::lonxml::get_all_text('/choice',
                    978:                                               $parser);
                    979:     my $nextstate = $token->[2]{'nextstate'};
1.13      bowersj2  980:     my $evalFlag = $token->[2]{'eval'};
                    981:     push @{$paramHash->{CHOICES}}, [$human, $computer, $nextstate, 
                    982:                                     $evalFlag];
1.5       bowersj2  983:     return '';
                    984: }
                    985: 
                    986: sub end_choice {
                    987:     return '';
                    988: }
                    989: 
                    990: sub render {
                    991:     # START HERE: Replace this with correct choices code.
                    992:     my $self = shift;
                    993:     my $var = $self->{'variable'};
                    994:     my $buttons = '';
                    995:     my $result = '';
                    996: 
                    997:     if ($self->{'multichoice'}) {
1.6       bowersj2  998:         $result .= <<SCRIPT;
1.5       bowersj2  999: <script>
1.18    ! bowersj2 1000:     function checkall(value, checkName) {
1.15      bowersj2 1001: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
1.18    ! bowersj2 1002:             ele = document.forms.helpform.elements[i];
        !          1003:             if (ele.name == checkName + '.forminput') {
        !          1004:                 document.forms.helpform.elements[i].checked=value;
        !          1005:             }
1.5       bowersj2 1006:         }
                   1007:     }
                   1008: </script>
                   1009: SCRIPT
                   1010:         $buttons = <<BUTTONS;
                   1011: <br />
1.18    ! bowersj2 1012: <input type="button" onclick="checkall(true, '$var')" value="Select All" />
        !          1013: <input type="button" onclick="checkall(false, '$var')" value="Unselect All" />
1.6       bowersj2 1014: <br />&nbsp;
1.5       bowersj2 1015: BUTTONS
                   1016:     }
                   1017: 
1.16      bowersj2 1018:     if (defined $self->{ERROR_MSG}) {
1.6       bowersj2 1019:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br />';
1.5       bowersj2 1020:     }
                   1021: 
                   1022:     $result .= $buttons;
1.6       bowersj2 1023:     
1.5       bowersj2 1024:     $result .= "<table>\n\n";
                   1025: 
                   1026:     my $type = "radio";
                   1027:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
                   1028:     my $checked = 0;
                   1029:     foreach my $choice (@{$self->{CHOICES}}) {
                   1030:         $result .= "<tr>\n<td width='20'>&nbsp;</td>\n";
                   1031:         $result .= "<td valign='top'><input type='$type' name='$var.forminput'"
                   1032:             . "' value='" . 
                   1033:             HTML::Entities::encode($choice->[1]) 
                   1034:             . "'";
                   1035:         if (!$self->{'multichoice'} && !$checked) {
                   1036:             $result .= " checked ";
                   1037:             $checked = 1;
                   1038:         }
1.13      bowersj2 1039:         my $choiceLabel = $choice->[0];
                   1040:         if ($choice->[4]) {  # if we need to evaluate this choice
                   1041:             $choiceLabel = "sub { my $helper = shift; my $state = shift;" .
                   1042:                 $choiceLabel . "}";
                   1043:             $choiceLabel = eval($choiceLabel);
                   1044:             $choiceLabel = &$choiceLabel($helper, $self);
                   1045:         }
                   1046:         $result .= "/></td><td> " . $choiceLabel . "</td></tr>\n";
1.5       bowersj2 1047:     }
                   1048:     $result .= "</table>\n\n\n";
                   1049:     $result .= $buttons;
                   1050: 
                   1051:     return $result;
                   1052: }
                   1053: 
                   1054: # If a NEXTSTATE was given or a nextstate for this choice was
                   1055: # given, switch to it
                   1056: sub postprocess {
                   1057:     my $self = shift;
                   1058:     my $chosenValue = $ENV{'form.' . $self->{'variable'} . '.forminput'};
                   1059: 
1.6       bowersj2 1060:     if (!$chosenValue) {
                   1061:         $self->{ERROR_MSG} = "You must choose one or more choices to" .
                   1062:             " continue.";
                   1063:         return 0;
                   1064:     }
                   1065: 
                   1066:     if ($self->{'multichoice'}) {
                   1067:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
                   1068:                                         $self->{'variable'});
                   1069:     }
                   1070: 
1.5       bowersj2 1071:     if (defined($self->{NEXTSTATE})) {
                   1072:         $helper->changeState($self->{NEXTSTATE});
                   1073:     }
                   1074:     
                   1075:     foreach my $choice (@{$self->{CHOICES}}) {
                   1076:         if ($choice->[1] eq $chosenValue) {
                   1077:             if (defined($choice->[2])) {
                   1078:                 $helper->changeState($choice->[2]);
                   1079:             }
                   1080:         }
                   1081:     }
1.6       bowersj2 1082:     return 1;
1.5       bowersj2 1083: }
                   1084: 1;
                   1085: 
                   1086: package Apache::lonhelper::date;
                   1087: 
                   1088: =pod
                   1089: 
                   1090: =head2 Element: date
                   1091: 
                   1092: Date elements allow the selection of a date with a drop down list.
                   1093: 
                   1094: Date elements can take two attributes:
                   1095: 
                   1096: =over 4
                   1097: 
                   1098: =item * B<variable>: The name of the variable to store the chosen
                   1099:         date in. Required.
                   1100: 
                   1101: =item * B<hoursminutes>: If a true value, the date will show hours
                   1102:         and minutes, as well as month/day/year. If false or missing,
                   1103:         the date will only show the month, day, and year.
                   1104: 
                   1105: =back
                   1106: 
                   1107: Date elements contain only an option <nextstate> tag to determine
                   1108: the next state.
                   1109: 
                   1110: Example:
                   1111: 
                   1112:  <date variable="DUE_DATE" hoursminutes="1">
                   1113:    <nextstate>choose_why</nextstate>
                   1114:    </date>
                   1115: 
                   1116: =cut
                   1117: 
                   1118: no strict;
                   1119: @ISA = ("Apache::lonhelper::element");
                   1120: use strict;
                   1121: 
                   1122: use Time::localtime;
                   1123: 
                   1124: BEGIN {
1.7       bowersj2 1125:     &Apache::lonhelper::register('Apache::lonhelper::date',
1.5       bowersj2 1126:                               ('date'));
                   1127: }
                   1128: 
                   1129: # Don't need to override the "new" from element
                   1130: sub new {
                   1131:     my $ref = Apache::lonhelper::element->new();
                   1132:     bless($ref);
                   1133: }
                   1134: 
                   1135: my @months = ("January", "February", "March", "April", "May", "June", "July",
                   1136: 	      "August", "September", "October", "November", "December");
                   1137: 
                   1138: # CONSTRUCTION: Construct the message element from the XML
                   1139: sub start_date {
                   1140:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1141: 
                   1142:     if ($target ne 'helper') {
                   1143:         return '';
                   1144:     }
                   1145: 
                   1146:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1147:     $helper->declareVar($paramHash->{'variable'});
                   1148:     $paramHash->{'hoursminutes'} = $token->[2]{'hoursminutes'};
                   1149: }
                   1150: 
                   1151: sub end_date {
                   1152:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1153: 
                   1154:     if ($target ne 'helper') {
                   1155:         return '';
                   1156:     }
                   1157:     Apache::lonhelper::date->new();
                   1158:     return '';
                   1159: }
                   1160: 
                   1161: sub render {
                   1162:     my $self = shift;
                   1163:     my $result = "";
                   1164:     my $var = $self->{'variable'};
                   1165: 
                   1166:     my $date;
                   1167:     
                   1168:     # Default date: The current hour.
                   1169:     $date = localtime();
                   1170:     $date->min(0);
                   1171: 
                   1172:     if (defined $self->{ERROR_MSG}) {
                   1173:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   1174:     }
                   1175: 
                   1176:     # Month
                   1177:     my $i;
                   1178:     $result .= "<select name='${var}month'>\n";
                   1179:     for ($i = 0; $i < 12; $i++) {
                   1180:         if ($i == $date->mon) {
                   1181:             $result .= "<option value='$i' selected>";
                   1182:         } else {
                   1183:             $result .= "<option value='$i'>";
                   1184:         }
                   1185:         $result .= $months[$i] . "</option>\n";
                   1186:     }
                   1187:     $result .= "</select>\n";
                   1188: 
                   1189:     # Day
                   1190:     $result .= "<select name='${var}day'>\n";
                   1191:     for ($i = 1; $i < 32; $i++) {
                   1192:         if ($i == $date->mday) {
                   1193:             $result .= '<option selected>';
                   1194:         } else {
                   1195:             $result .= '<option>';
                   1196:         }
                   1197:         $result .= "$i</option>\n";
                   1198:     }
                   1199:     $result .= "</select>,\n";
                   1200: 
                   1201:     # Year
                   1202:     $result .= "<select name='${var}year'>\n";
                   1203:     for ($i = 2000; $i < 2030; $i++) { # update this after 64-bit dates
                   1204:         if ($date->year + 1900 == $i) {
                   1205:             $result .= "<option selected>";
                   1206:         } else {
                   1207:             $result .= "<option>";
                   1208:         }
                   1209:         $result .= "$i</option>\n";
                   1210:     }
                   1211:     $result .= "</select>,\n";
                   1212: 
                   1213:     # Display Hours and Minutes if they are called for
                   1214:     if ($self->{'hoursminutes'}) {
                   1215:         # Build hour
                   1216:         $result .= "<select name='${var}hour'>\n";
                   1217:         $result .= "<option " . ($date->hour == 0 ? 'selected ':'') .
                   1218:             " value='0'>midnight</option>\n";
                   1219:         for ($i = 1; $i < 12; $i++) {
                   1220:             if ($date->hour == $i) {
                   1221:                 $result .= "<option selected value='$i'>$i a.m.</option>\n";
                   1222:             } else {
                   1223:                 $result .= "<option value='$i'>$i a.m</option>\n";
                   1224:             }
                   1225:         }
                   1226:         $result .= "<option " . ($date->hour == 12 ? 'selected ':'') .
                   1227:             " value='12'>noon</option>\n";
                   1228:         for ($i = 13; $i < 24; $i++) {
                   1229:             my $printedHour = $i - 12;
                   1230:             if ($date->hour == $i) {
                   1231:                 $result .= "<option selected value='$i'>$printedHour p.m.</option>\n";
                   1232:             } else {
                   1233:                 $result .= "<option value='$i'>$printedHour p.m.</option>\n";
                   1234:             }
                   1235:         }
                   1236: 
                   1237:         $result .= "</select> :\n";
                   1238: 
                   1239:         $result .= "<select name='${var}minute'>\n";
                   1240:         for ($i = 0; $i < 60; $i++) {
                   1241:             my $printedMinute = $i;
                   1242:             if ($i < 10) {
                   1243:                 $printedMinute = "0" . $printedMinute;
                   1244:             }
                   1245:             if ($date->min == $i) {
                   1246:                 $result .= "<option selected>";
                   1247:             } else {
                   1248:                 $result .= "<option>";
                   1249:             }
                   1250:             $result .= "$printedMinute</option>\n";
                   1251:         }
                   1252:         $result .= "</select>\n";
                   1253:     }
                   1254: 
                   1255:     return $result;
                   1256: 
                   1257: }
                   1258: # If a NEXTSTATE was given, switch to it
                   1259: sub postprocess {
                   1260:     my $self = shift;
                   1261:     my $var = $self->{'variable'};
                   1262:     my $month = $ENV{'form.' . $var . 'month'}; 
                   1263:     my $day = $ENV{'form.' . $var . 'day'}; 
                   1264:     my $year = $ENV{'form.' . $var . 'year'}; 
                   1265:     my $min = 0; 
                   1266:     my $hour = 0;
                   1267:     if ($self->{'hoursminutes'}) {
                   1268:         $min = $ENV{'form.' . $var . 'minute'};
                   1269:         $hour = $ENV{'form.' . $var . 'hour'};
                   1270:     }
                   1271: 
                   1272:     my $chosenDate = Time::Local::timelocal(0, $min, $hour, $day, $month, $year);
                   1273:     # Check to make sure that the date was not automatically co-erced into a 
                   1274:     # valid date, as we want to flag that as an error
                   1275:     # This happens for "Feb. 31", for instance, which is coerced to March 2 or
                   1276:     # 3, depending on if it's a leapyear
                   1277:     my $checkDate = localtime($chosenDate);
                   1278: 
                   1279:     if ($checkDate->mon != $month || $checkDate->mday != $day ||
                   1280:         $checkDate->year + 1900 != $year) {
                   1281:         $self->{ERROR_MSG} = "Can't use " . $months[$month] . " $day, $year as a "
                   1282:             . "date because it doesn't exist. Please enter a valid date.";
1.6       bowersj2 1283:         return 0;
1.5       bowersj2 1284:     }
                   1285: 
                   1286:     $helper->{VARS}->{$var} = $chosenDate;
                   1287: 
                   1288:     if (defined($self->{NEXTSTATE})) {
                   1289:         $helper->changeState($self->{NEXTSTATE});
                   1290:     }
1.6       bowersj2 1291: 
                   1292:     return 1;
1.5       bowersj2 1293: }
                   1294: 1;
                   1295: 
                   1296: package Apache::lonhelper::resource;
                   1297: 
                   1298: =pod
                   1299: 
                   1300: =head2 Element: resource
                   1301: 
                   1302: <resource> elements allow the user to select one or multiple resources
                   1303: from the current course. You can filter out which resources they can view,
                   1304: and filter out which resources they can select. The course will always
                   1305: be displayed fully expanded, because of the difficulty of maintaining
                   1306: selections across folder openings and closings. If this is fixed, then
                   1307: the user can manipulate the folders.
                   1308: 
                   1309: <resource> takes the standard variable attribute to control what helper
                   1310: variable stores the results. It also takes a "multichoice" attribute,
1.17      bowersj2 1311: which controls whether the user can select more then one resource. The 
                   1312: "toponly" attribute controls whether the resource display shows just the
                   1313: resources in that sequence, or recurses into all sub-sequences, defaulting
                   1314: to false.
1.5       bowersj2 1315: 
                   1316: B<SUB-TAGS>
                   1317: 
                   1318: =over 4
                   1319: 
                   1320: =item * <filterfunc>: If you want to filter what resources are displayed
                   1321:   to the user, use a filter func. The <filterfunc> tag should contain
                   1322:   Perl code that when wrapped with "sub { my $res = shift; " and "}" is 
                   1323:   a function that returns true if the resource should be displayed, 
                   1324:   and false if it should be skipped. $res is a resource object. 
                   1325:   (See Apache::lonnavmaps documentation for information about the 
                   1326:   resource object.)
                   1327: 
                   1328: =item * <choicefunc>: Same as <filterfunc>, except that controls whether
                   1329:   the given resource can be chosen. (It is almost always a good idea to
                   1330:   show the user the folders, for instance, but you do not always want to 
                   1331:   let the user select them.)
                   1332: 
                   1333: =item * <nextstate>: Standard nextstate behavior.
                   1334: 
                   1335: =item * <valuefunc>: This function controls what is returned by the resource
                   1336:   when the user selects it. Like filterfunc and choicefunc, it should be
                   1337:   a function fragment that when wrapped by "sub { my $res = shift; " and
                   1338:   "}" returns a string representing what you want to have as the value. By
                   1339:   default, the value will be the resource ID of the object ($res->{ID}).
                   1340: 
1.13      bowersj2 1341: =item * <mapurl>: If the URL of a map is given here, only that map
                   1342:   will be displayed, instead of the whole course.
                   1343: 
1.5       bowersj2 1344: =back
                   1345: 
                   1346: =cut
                   1347: 
                   1348: no strict;
                   1349: @ISA = ("Apache::lonhelper::element");
                   1350: use strict;
                   1351: 
                   1352: BEGIN {
1.7       bowersj2 1353:     &Apache::lonhelper::register('Apache::lonhelper::resource',
1.5       bowersj2 1354:                               ('resource', 'filterfunc', 
1.13      bowersj2 1355:                                'choicefunc', 'valuefunc',
                   1356:                                'mapurl'));
1.5       bowersj2 1357: }
                   1358: 
                   1359: sub new {
                   1360:     my $ref = Apache::lonhelper::element->new();
                   1361:     bless($ref);
                   1362: }
                   1363: 
                   1364: # CONSTRUCTION: Construct the message element from the XML
                   1365: sub start_resource {
                   1366:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1367: 
                   1368:     if ($target ne 'helper') {
                   1369:         return '';
                   1370:     }
                   1371: 
                   1372:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1373:     $helper->declareVar($paramHash->{'variable'});
1.14      bowersj2 1374:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.17      bowersj2 1375:     $paramHash->{'toponly'} = $token->[2]{'toponly'};
1.5       bowersj2 1376:     return '';
                   1377: }
                   1378: 
                   1379: sub end_resource {
                   1380:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1381: 
                   1382:     if ($target ne 'helper') {
                   1383:         return '';
                   1384:     }
                   1385:     if (!defined($paramHash->{FILTER_FUNC})) {
                   1386:         $paramHash->{FILTER_FUNC} = sub {return 1;};
                   1387:     }
                   1388:     if (!defined($paramHash->{CHOICE_FUNC})) {
                   1389:         $paramHash->{CHOICE_FUNC} = sub {return 1;};
                   1390:     }
                   1391:     if (!defined($paramHash->{VALUE_FUNC})) {
                   1392:         $paramHash->{VALUE_FUNC} = sub {my $res = shift; return $res->{ID}; };
                   1393:     }
                   1394:     Apache::lonhelper::resource->new();
1.4       bowersj2 1395:     return '';
                   1396: }
                   1397: 
1.5       bowersj2 1398: sub start_filterfunc {
                   1399:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1400: 
                   1401:     if ($target ne 'helper') {
                   1402:         return '';
                   1403:     }
                   1404: 
                   1405:     my $contents = Apache::lonxml::get_all_text('/filterfunc',
                   1406:                                                 $parser);
                   1407:     $contents = 'sub { my $res = shift; ' . $contents . '}';
                   1408:     $paramHash->{FILTER_FUNC} = eval $contents;
                   1409: }
                   1410: 
                   1411: sub end_filterfunc { return ''; }
                   1412: 
                   1413: sub start_choicefunc {
                   1414:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1415: 
                   1416:     if ($target ne 'helper') {
                   1417:         return '';
                   1418:     }
                   1419: 
                   1420:     my $contents = Apache::lonxml::get_all_text('/choicefunc',
                   1421:                                                 $parser);
                   1422:     $contents = 'sub { my $res = shift; ' . $contents . '}';
                   1423:     $paramHash->{CHOICE_FUNC} = eval $contents;
                   1424: }
                   1425: 
                   1426: sub end_choicefunc { return ''; }
                   1427: 
                   1428: sub start_valuefunc {
                   1429:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1430: 
                   1431:     if ($target ne 'helper') {
                   1432:         return '';
                   1433:     }
                   1434: 
                   1435:     my $contents = Apache::lonxml::get_all_text('/valuefunc',
                   1436:                                                 $parser);
                   1437:     $contents = 'sub { my $res = shift; ' . $contents . '}';
                   1438:     $paramHash->{VALUE_FUNC} = eval $contents;
                   1439: }
                   1440: 
                   1441: sub end_valuefunc { return ''; }
                   1442: 
1.13      bowersj2 1443: sub start_mapurl {
                   1444:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1445: 
                   1446:     if ($target ne 'helper') {
                   1447:         return '';
                   1448:     }
                   1449: 
                   1450:     my $contents = Apache::lonxml::get_all_text('/mapurl',
                   1451:                                                 $parser);
1.14      bowersj2 1452:     $paramHash->{MAP_URL} = $contents;
1.13      bowersj2 1453: }
                   1454: 
                   1455: sub end_mapurl { return ''; }
                   1456: 
1.5       bowersj2 1457: # A note, in case I don't get to this before I leave.
                   1458: # If someone complains about the "Back" button returning them
                   1459: # to the previous folder state, instead of returning them to
                   1460: # the previous helper state, the *correct* answer is for the helper
                   1461: # to keep track of how many times the user has manipulated the folders,
                   1462: # and feed that to the history.go() call in the helper rendering routines.
                   1463: # If done correctly, the helper itself can keep track of how many times
                   1464: # it renders the same states, so it doesn't go in just this state, and
                   1465: # you can lean on the browser back button to make sure it all chains
                   1466: # correctly.
                   1467: # Right now, though, I'm just forcing all folders open.
                   1468: 
                   1469: sub render {
                   1470:     my $self = shift;
                   1471:     my $result = "";
                   1472:     my $var = $self->{'variable'};
                   1473:     my $curVal = $helper->{VARS}->{$var};
                   1474: 
1.15      bowersj2 1475:     my $buttons = '';
                   1476: 
                   1477:     if ($self->{'multichoice'}) {
                   1478:         $result = <<SCRIPT;
                   1479: <script>
1.18    ! bowersj2 1480:     function checkall(value, checkName) {
1.15      bowersj2 1481: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
                   1482:             ele = document.forms.helpform.elements[i];
1.18    ! bowersj2 1483:             if (ele.name == checkName + '.forminput') {
1.15      bowersj2 1484:                 document.forms.helpform.elements[i].checked=value;
                   1485:             }
                   1486:         }
                   1487:     }
                   1488: </script>
                   1489: SCRIPT
                   1490:         $buttons = <<BUTTONS;
                   1491: <br /> &nbsp;
1.18    ! bowersj2 1492: <input type="button" onclick="checkall(true, '$var')" value="Select All Resources" />
        !          1493: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Resources" />
1.15      bowersj2 1494: <br /> &nbsp;
                   1495: BUTTONS
                   1496:     }
                   1497: 
1.5       bowersj2 1498:     if (defined $self->{ERROR_MSG}) {
1.14      bowersj2 1499:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
1.5       bowersj2 1500:     }
                   1501: 
1.15      bowersj2 1502:     $result .= $buttons;
                   1503: 
1.5       bowersj2 1504:     my $filterFunc = $self->{FILTER_FUNC};
                   1505:     my $choiceFunc = $self->{CHOICE_FUNC};
                   1506:     my $valueFunc = $self->{VALUE_FUNC};
1.13      bowersj2 1507:     my $mapUrl = $self->{MAP_URL};
1.14      bowersj2 1508:     my $multichoice = $self->{'multichoice'};
1.5       bowersj2 1509: 
                   1510:     # Create the composite function that renders the column on the nav map
                   1511:     # have to admit any language that lets me do this can't be all bad
                   1512:     #  - Jeremy (Pythonista) ;-)
                   1513:     my $checked = 0;
                   1514:     my $renderColFunc = sub {
                   1515:         my ($resource, $part, $params) = @_;
1.14      bowersj2 1516: 
                   1517:         my $inputType;
                   1518:         if ($multichoice) { $inputType = 'checkbox'; }
                   1519:         else {$inputType = 'radio'; }
                   1520: 
1.5       bowersj2 1521:         if (!&$choiceFunc($resource)) {
                   1522:             return '<td>&nbsp;</td>';
                   1523:         } else {
1.14      bowersj2 1524:             my $col = "<td><input type='$inputType' name='${var}.forminput' ";
                   1525:             if (!$checked && !$multichoice) {
1.5       bowersj2 1526:                 $col .= "checked ";
                   1527:                 $checked = 1;
                   1528:             }
                   1529:             $col .= "value='" . 
                   1530:                 HTML::Entities::encode(&$valueFunc($resource)) 
                   1531:                 . "' /></td>";
                   1532:             return $col;
                   1533:         }
                   1534:     };
                   1535: 
1.17      bowersj2 1536:     $ENV{'form.condition'} = !$self->{'toponly'};
1.5       bowersj2 1537:     $result .= 
                   1538:         &Apache::lonnavmaps::render( { 'cols' => [$renderColFunc, 
                   1539:                                                   Apache::lonnavmaps::resource()],
                   1540:                                        'showParts' => 0,
                   1541:                                        'filterFunc' => $filterFunc,
1.13      bowersj2 1542:                                        'resource_no_folder_link' => 1,
                   1543:                                        'iterator_map' => $mapUrl }
1.5       bowersj2 1544:                                        );
1.15      bowersj2 1545: 
                   1546:     $result .= $buttons;
1.5       bowersj2 1547:                                                 
                   1548:     return $result;
                   1549: }
                   1550:     
                   1551: sub postprocess {
                   1552:     my $self = shift;
1.14      bowersj2 1553: 
                   1554:     if ($self->{'multichoice'}) {
                   1555:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
                   1556:                                         $self->{'variable'});
                   1557:     }
                   1558: 
                   1559:     if ($self->{'multichoice'} && !$helper->{VARS}->{$self->{'variable'}}) {
                   1560:         $self->{ERROR_MSG} = 'You must choose at least one resource to continue.';
                   1561:         return 0;
                   1562:     }
                   1563: 
1.5       bowersj2 1564:     if (defined($self->{NEXTSTATE})) {
                   1565:         $helper->changeState($self->{NEXTSTATE});
                   1566:     }
1.6       bowersj2 1567: 
                   1568:     return 1;
1.5       bowersj2 1569: }
                   1570: 
                   1571: 1;
                   1572: 
                   1573: package Apache::lonhelper::student;
                   1574: 
                   1575: =pod
                   1576: 
                   1577: =head2 Element: student
                   1578: 
                   1579: Student elements display a choice of students enrolled in the current
                   1580: course. Currently it is primitive; this is expected to evolve later.
                   1581: 
                   1582: Student elements take two attributes: "variable", which means what
                   1583: it usually does, and "multichoice", which if true allows the user
                   1584: to select multiple students.
                   1585: 
                   1586: =cut
                   1587: 
                   1588: no strict;
                   1589: @ISA = ("Apache::lonhelper::element");
                   1590: use strict;
                   1591: 
                   1592: 
                   1593: 
                   1594: BEGIN {
1.7       bowersj2 1595:     &Apache::lonhelper::register('Apache::lonhelper::student',
1.5       bowersj2 1596:                               ('student'));
                   1597: }
                   1598: 
                   1599: sub new {
                   1600:     my $ref = Apache::lonhelper::element->new();
                   1601:     bless($ref);
                   1602: }
1.4       bowersj2 1603: 
1.5       bowersj2 1604: sub start_student {
1.4       bowersj2 1605:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1606: 
                   1607:     if ($target ne 'helper') {
                   1608:         return '';
                   1609:     }
                   1610: 
1.5       bowersj2 1611:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1612:     $helper->declareVar($paramHash->{'variable'});
                   1613:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.12      bowersj2 1614:     if (defined($token->[2]{'nextstate'})) {
                   1615:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
                   1616:     }
                   1617:     
1.5       bowersj2 1618: }    
                   1619: 
                   1620: sub end_student {
                   1621:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1622: 
                   1623:     if ($target ne 'helper') {
                   1624:         return '';
                   1625:     }
                   1626:     Apache::lonhelper::student->new();
1.3       bowersj2 1627: }
1.5       bowersj2 1628: 
                   1629: sub render {
                   1630:     my $self = shift;
                   1631:     my $result = '';
                   1632:     my $buttons = '';
1.18    ! bowersj2 1633:     my $var = $self->{'variable'};
1.5       bowersj2 1634: 
                   1635:     if ($self->{'multichoice'}) {
                   1636:         $result = <<SCRIPT;
                   1637: <script>
1.18    ! bowersj2 1638:     function checkall(value, checkName) {
1.15      bowersj2 1639: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
1.18    ! bowersj2 1640:             ele = document.forms.helpform.elements[i];
        !          1641:             if (ele.name == checkName + '.forminput') {
        !          1642:                 document.forms.helpform.elements[i].checked=value;
        !          1643:             }
1.5       bowersj2 1644:         }
                   1645:     }
                   1646: </script>
                   1647: SCRIPT
                   1648:         $buttons = <<BUTTONS;
                   1649: <br />
1.18    ! bowersj2 1650: <input type="button" onclick="checkall(true, '$var')" value="Select All Students" />
        !          1651: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Students" />
1.5       bowersj2 1652: <br />
                   1653: BUTTONS
                   1654:     }
                   1655: 
                   1656:     if (defined $self->{ERROR_MSG}) {
                   1657:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   1658:     }
                   1659: 
                   1660:     # Load up the students
                   1661:     my $choices = &Apache::loncoursedata::get_classlist();
                   1662:     my @keys = keys %{$choices};
                   1663: 
                   1664:     # Constants
                   1665:     my $section = Apache::loncoursedata::CL_SECTION();
                   1666:     my $fullname = Apache::loncoursedata::CL_FULLNAME();
                   1667: 
                   1668:     # Sort by: Section, name
                   1669:     @keys = sort {
                   1670:         if ($choices->{$a}->[$section] ne $choices->{$b}->[$section]) {
                   1671:             return $choices->{$a}->[$section] cmp $choices->{$b}->[$section];
                   1672:         }
                   1673:         return $choices->{$a}->[$fullname] cmp $choices->{$b}->[$fullname];
                   1674:     } @keys;
                   1675: 
                   1676:     my $type = 'radio';
                   1677:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
                   1678:     $result .= "<table cellspacing='2' cellpadding='2' border='0'>\n";
                   1679:     $result .= "<tr><td></td><td align='center'><b>Student Name</b></td>".
                   1680:         "<td align='center'><b>Section</b></td></tr>";
                   1681: 
                   1682:     my $checked = 0;
                   1683:     foreach (@keys) {
                   1684:         $result .= "<tr><td><input type='$type' name='" .
                   1685:             $self->{'variable'} . '.forminput' . "'";
                   1686:             
                   1687:         if (!$self->{'multichoice'} && !$checked) {
                   1688:             $result .= " checked ";
                   1689:             $checked = 1;
                   1690:         }
                   1691:         $result .=
                   1692:             " value='" . HTML::Entities::encode($_)
                   1693:             . "' /></td><td>"
                   1694:             . HTML::Entities::encode($choices->{$_}->[$fullname])
                   1695:             . "</td><td align='center'>" 
                   1696:             . HTML::Entities::encode($choices->{$_}->[$section])
                   1697:             . "</td></tr>\n";
                   1698:     }
                   1699: 
                   1700:     $result .= "</table>\n\n";
                   1701:     $result .= $buttons;    
1.4       bowersj2 1702:     
1.5       bowersj2 1703:     return $result;
                   1704: }
                   1705: 
1.6       bowersj2 1706: sub postprocess {
                   1707:     my $self = shift;
                   1708: 
                   1709:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
                   1710:     if (!$result) {
                   1711:         $self->{ERROR_MSG} = 'You must choose at least one student '.
                   1712:             'to continue.';
                   1713:         return 0;
                   1714:     }
                   1715: 
                   1716:     if ($self->{'multichoice'}) {
                   1717:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
                   1718:                                         $self->{'variable'});
                   1719:     }
                   1720:     if (defined($self->{NEXTSTATE})) {
                   1721:         $helper->changeState($self->{NEXTSTATE});
                   1722:     }
                   1723: 
                   1724:     return 1;
                   1725: }
                   1726: 
1.5       bowersj2 1727: 1;
                   1728: 
                   1729: package Apache::lonhelper::files;
                   1730: 
                   1731: =pod
                   1732: 
                   1733: =head2 Element: files
                   1734: 
                   1735: files allows the users to choose files from a given directory on the
                   1736: server. It is always multichoice and stores the result as a triple-pipe
                   1737: delimited entry in the helper variables. 
                   1738: 
                   1739: Since it is extremely unlikely that you can actually code a constant
                   1740: representing the directory you wish to allow the user to search, <files>
                   1741: takes a subroutine that returns the name of the directory you wish to
                   1742: have the user browse.
                   1743: 
                   1744: files accepts the attribute "variable" to control where the files chosen
                   1745: are put. It accepts the attribute "multichoice" as the other attribute,
                   1746: defaulting to false, which if true will allow the user to select more
                   1747: then one choice. 
                   1748: 
                   1749: <files> accepts three subtags. One is the "nextstate" sub-tag that works
                   1750: as it does with the other tags. Another is a <filechoice> sub tag that
                   1751: is Perl code that, when surrounded by "sub {" and "}" will return a
                   1752: string representing what directory on the server to allow the user to 
                   1753: choose files from. Finally, the <filefilter> subtag should contain Perl
                   1754: code that when surrounded by "sub { my $filename = shift; " and "}",
                   1755: returns a true value if the user can pick that file, or false otherwise.
                   1756: The filename passed to the function will be just the name of the file, 
                   1757: with no path info.
                   1758: 
                   1759: =cut
                   1760: 
                   1761: no strict;
                   1762: @ISA = ("Apache::lonhelper::element");
                   1763: use strict;
                   1764: 
                   1765: BEGIN {
1.7       bowersj2 1766:     &Apache::lonhelper::register('Apache::lonhelper::files',
                   1767:                                  ('files', 'filechoice', 'filefilter'));
1.5       bowersj2 1768: }
                   1769: 
                   1770: sub new {
                   1771:     my $ref = Apache::lonhelper::element->new();
                   1772:     bless($ref);
                   1773: }
                   1774: 
                   1775: sub start_files {
                   1776:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1777: 
                   1778:     if ($target ne 'helper') {
                   1779:         return '';
                   1780:     }
                   1781:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1782:     $helper->declareVar($paramHash->{'variable'});
                   1783:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
                   1784: }    
                   1785: 
                   1786: sub end_files {
                   1787:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1788: 
                   1789:     if ($target ne 'helper') {
                   1790:         return '';
                   1791:     }
                   1792:     if (!defined($paramHash->{FILTER_FUNC})) {
                   1793:         $paramHash->{FILTER_FUNC} = sub { return 1; };
                   1794:     }
                   1795:     Apache::lonhelper::files->new();
                   1796: }    
                   1797: 
                   1798: sub start_filechoice {
                   1799:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1800: 
                   1801:     if ($target ne 'helper') {
                   1802:         return '';
                   1803:     }
                   1804:     $paramHash->{'filechoice'} = Apache::lonxml::get_all_text('/filechoice',
                   1805:                                                               $parser);
                   1806: }
                   1807: 
                   1808: sub end_filechoice { return ''; }
                   1809: 
                   1810: sub start_filefilter {
                   1811:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1812: 
                   1813:     if ($target ne 'helper') {
                   1814:         return '';
                   1815:     }
                   1816: 
                   1817:     my $contents = Apache::lonxml::get_all_text('/filefilter',
                   1818:                                                 $parser);
                   1819:     $contents = 'sub { my $filename = shift; ' . $contents . '}';
                   1820:     $paramHash->{FILTER_FUNC} = eval $contents;
                   1821: }
                   1822: 
                   1823: sub end_filefilter { return ''; }
1.3       bowersj2 1824: 
                   1825: sub render {
                   1826:     my $self = shift;
1.5       bowersj2 1827:     my $result = '';
                   1828:     my $var = $self->{'variable'};
                   1829:     
                   1830:     my $subdirFunc = eval('sub {' . $self->{'filechoice'} . '}');
1.11      bowersj2 1831:     die 'Error in resource filter code for variable ' . 
                   1832:         {'variable'} . ', Perl said:' . $@ if $@;
                   1833: 
1.5       bowersj2 1834:     my $subdir = &$subdirFunc();
                   1835: 
                   1836:     my $filterFunc = $self->{FILTER_FUNC};
                   1837:     my $buttons = '';
                   1838: 
                   1839:     if ($self->{'multichoice'}) {
                   1840:         $result = <<SCRIPT;
                   1841: <script>
1.18    ! bowersj2 1842:     function checkall(value, checkName) {
1.15      bowersj2 1843: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
                   1844:             ele = document.forms.helpform.elements[i];
1.18    ! bowersj2 1845:             if (ele.name == checkName + '.forminput') {
1.15      bowersj2 1846:                 document.forms.helpform.elements[i].checked=value;
1.5       bowersj2 1847:             }
                   1848:         }
                   1849:     }
                   1850: </script>
                   1851: SCRIPT
1.15      bowersj2 1852:         $buttons = <<BUTTONS;
1.5       bowersj2 1853: <br /> &nbsp;
1.18    ! bowersj2 1854: <input type="button" onclick="checkall(true, '$var')" value="Select All Files" />
        !          1855: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Files" />
1.5       bowersj2 1856: <br /> &nbsp;
                   1857: BUTTONS
                   1858:     }
                   1859: 
                   1860:     # Get the list of files in this directory.
                   1861:     my @fileList;
                   1862: 
                   1863:     # If the subdirectory is in local CSTR space
                   1864:     if ($subdir =~ m|/home/([^/]+)/public_html|) {
                   1865:         my $user = $1;
                   1866:         my $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
                   1867:         @fileList = &Apache::lonnet::dirlist($subdir, $domain, $user, '');
                   1868:     } else {
                   1869:         # local library server resource space
                   1870:         @fileList = &Apache::lonnet::dirlist($subdir, $ENV{'user.domain'}, $ENV{'user.name'}, '');
                   1871:     }
1.3       bowersj2 1872: 
1.5       bowersj2 1873:     $result .= $buttons;
                   1874: 
1.6       bowersj2 1875:     if (defined $self->{ERROR_MSG}) {
                   1876:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   1877:     }
                   1878: 
1.5       bowersj2 1879:     $result .= '<table border="0" cellpadding="1" cellspacing="1">';
                   1880: 
                   1881:     # Keeps track if there are no choices, prints appropriate error
                   1882:     # if there are none. 
                   1883:     my $choices = 0;
                   1884:     my $type = 'radio';
                   1885:     if ($self->{'multichoice'}) {
                   1886:         $type = 'checkbox';
                   1887:     }
                   1888:     # Print each legitimate file choice.
                   1889:     for my $file (@fileList) {
                   1890:         $file = (split(/&/, $file))[0];
                   1891:         if ($file eq '.' || $file eq '..') {
                   1892:             next;
                   1893:         }
                   1894:         my $fileName = $subdir .'/'. $file;
                   1895:         if (&$filterFunc($file)) {
                   1896:             $result .= '<tr><td align="right">' .
                   1897:                 "<input type='$type' name='" . $var
                   1898:             . ".forminput' value='" . HTML::Entities::encode($fileName) .
                   1899:                 "'";
                   1900:             if (!$self->{'multichoice'} && $choices == 0) {
                   1901:                 $result .= ' checked';
                   1902:             }
                   1903:             $result .= "/></td><td>" . $file . "</td></tr>\n";
                   1904:             $choices++;
                   1905:         }
                   1906:     }
                   1907: 
                   1908:     $result .= "</table>\n";
                   1909: 
                   1910:     if (!$choices) {
                   1911:         $result .= '<font color="#FF0000">There are no files available to select in this directory. Please go back and select another option.</font><br /><br />';
                   1912:     }
                   1913: 
                   1914:     $result .= $buttons;
                   1915: 
                   1916:     return $result;
1.4       bowersj2 1917: }
1.5       bowersj2 1918: 
1.4       bowersj2 1919: sub postprocess {
                   1920:     my $self = shift;
1.6       bowersj2 1921:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
                   1922:     if (!$result) {
                   1923:         $self->{ERROR_MSG} = 'You must choose at least one file '.
                   1924:             'to continue.';
                   1925:         return 0;
                   1926:     }
                   1927: 
1.5       bowersj2 1928:     if ($self->{'multichoice'}) {
                   1929:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
                   1930:                                         $self->{'variable'});
                   1931:     }
                   1932:     if (defined($self->{NEXTSTATE})) {
                   1933:         $helper->changeState($self->{NEXTSTATE});
1.3       bowersj2 1934:     }
1.6       bowersj2 1935: 
                   1936:     return 1;
1.3       bowersj2 1937: }
1.8       bowersj2 1938: 
                   1939: 1;
                   1940: 
1.11      bowersj2 1941: package Apache::lonhelper::section;
                   1942: 
                   1943: =pod
                   1944: 
                   1945: =head2 Element: section
                   1946: 
                   1947: <section> allows the user to choose one or more sections from the current
                   1948: course.
                   1949: 
                   1950: It takes the standard attributes "variable", "multichoice", and
                   1951: "nextstate", meaning what they do for most other elements.
                   1952: 
                   1953: =cut
                   1954: 
                   1955: no strict;
                   1956: @ISA = ("Apache::lonhelper::choices");
                   1957: use strict;
                   1958: 
                   1959: BEGIN {
                   1960:     &Apache::lonhelper::register('Apache::lonhelper::section',
                   1961:                                  ('section'));
                   1962: }
                   1963: 
                   1964: sub new {
                   1965:     my $ref = Apache::lonhelper::choices->new();
                   1966:     bless($ref);
                   1967: }
                   1968: 
                   1969: sub start_section {
                   1970:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1971: 
                   1972:     if ($target ne 'helper') {
                   1973:         return '';
                   1974:     }
1.12      bowersj2 1975: 
                   1976:     $paramHash->{CHOICES} = [];
                   1977: 
1.11      bowersj2 1978:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1979:     $helper->declareVar($paramHash->{'variable'});
                   1980:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
                   1981:     if (defined($token->[2]{'nextstate'})) {
1.12      bowersj2 1982:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
1.11      bowersj2 1983:     }
                   1984: 
                   1985:     # Populate the CHOICES element
                   1986:     my %choices;
                   1987: 
                   1988:     my $section = Apache::loncoursedata::CL_SECTION();
                   1989:     my $classlist = Apache::loncoursedata::get_classlist();
                   1990:     foreach (keys %$classlist) {
                   1991:         my $sectionName = $classlist->{$_}->[$section];
                   1992:         if (!$sectionName) {
                   1993:             $choices{"No section assigned"} = "";
                   1994:         } else {
                   1995:             $choices{$sectionName} = $sectionName;
                   1996:         }
1.12      bowersj2 1997:     } 
                   1998:    
1.11      bowersj2 1999:     for my $sectionName (sort(keys(%choices))) {
1.12      bowersj2 2000:         
1.11      bowersj2 2001:         push @{$paramHash->{CHOICES}}, [$sectionName, $sectionName];
                   2002:     }
                   2003: }    
                   2004: 
1.12      bowersj2 2005: sub end_section {
                   2006:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.11      bowersj2 2007: 
1.12      bowersj2 2008:     if ($target ne 'helper') {
                   2009:         return '';
                   2010:     }
                   2011:     Apache::lonhelper::section->new();
                   2012: }    
1.11      bowersj2 2013: 1;
                   2014: 
1.8       bowersj2 2015: package Apache::lonhelper::general;
                   2016: 
                   2017: =pod
                   2018: 
                   2019: =head2 General-purpose tag: <exec>
                   2020: 
                   2021: The contents of the exec tag are executed as Perl code, not inside a 
                   2022: safe space, so the full range of $ENV and such is available. The code
                   2023: will be executed as a subroutine wrapped with the following code:
                   2024: 
                   2025: "sub { my $helper = shift; my $state = shift;" and
                   2026: 
                   2027: "}"
                   2028: 
                   2029: The return value is ignored.
                   2030: 
                   2031: $helper is the helper object. Feel free to add methods to the helper
                   2032: object to support whatever manipulation you may need to do (for instance,
                   2033: overriding the form location if the state is the final state; see 
                   2034: lonparm.helper for an example).
                   2035: 
                   2036: $state is the $paramHash that has currently been generated and may
                   2037: be manipulated by the code in exec. Note that the $state is not yet
                   2038: an actual state B<object>, it is just a hash, so do not expect to
                   2039: be able to call methods on it.
                   2040: 
                   2041: =cut
                   2042: 
                   2043: BEGIN {
                   2044:     &Apache::lonhelper::register('Apache::lonhelper::general',
1.11      bowersj2 2045:                                  'exec', 'condition', 'clause',
                   2046:                                  'eval');
1.8       bowersj2 2047: }
                   2048: 
                   2049: sub start_exec {
                   2050:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2051: 
                   2052:     if ($target ne 'helper') {
                   2053:         return '';
                   2054:     }
                   2055:     
                   2056:     my $code = &Apache::lonxml::get_all_text('/exec', $parser);
                   2057:     
                   2058:     $code = eval ('sub { my $helper = shift; my $state = shift; ' .
                   2059:         $code . "}");
1.11      bowersj2 2060:     die 'Error in <exec>, Perl said: '. $@ if $@;
1.8       bowersj2 2061:     &$code($helper, $paramHash);
                   2062: }
                   2063: 
                   2064: sub end_exec { return ''; }
                   2065: 
                   2066: =pod
                   2067: 
                   2068: =head2 General-purpose tag: <condition>
                   2069: 
                   2070: The <condition> tag allows you to mask out parts of the helper code
                   2071: depending on some programatically determined condition. The condition
                   2072: tag contains a tag <clause> which contains perl code that when wrapped
                   2073: with "sub { my $helper = shift; my $state = shift; " and "}", returns
                   2074: a true value if the XML in the condition should be evaluated as a normal
                   2075: part of the helper, or false if it should be completely discarded.
                   2076: 
                   2077: The <clause> tag must be the first sub-tag of the <condition> tag or
                   2078: it will not work as expected.
                   2079: 
                   2080: =cut
                   2081: 
                   2082: # The condition tag just functions as a marker, it doesn't have
                   2083: # to "do" anything. Technically it doesn't even have to be registered
                   2084: # with the lonxml code, but I leave this here to be explicit about it.
                   2085: sub start_condition { return ''; }
                   2086: sub end_condition { return ''; }
                   2087: 
                   2088: sub start_clause {
                   2089:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2090: 
                   2091:     if ($target ne 'helper') {
                   2092:         return '';
                   2093:     }
                   2094:     
                   2095:     my $clause = Apache::lonxml::get_all_text('/clause', $parser);
                   2096:     $clause = eval('sub { my $helper = shift; my $state = shift; '
                   2097:         . $clause . '}');
1.11      bowersj2 2098:     die 'Error in clause of condition, Perl said: ' . $@ if $@;
1.8       bowersj2 2099:     if (!&$clause($helper, $paramHash)) {
                   2100:         # Discard all text until the /condition.
                   2101:         &Apache::lonxml::get_all_text('/condition', $parser);
                   2102:     }
                   2103: }
                   2104: 
                   2105: sub end_clause { return ''; }
1.11      bowersj2 2106: 
                   2107: =pod
                   2108: 
                   2109: =head2 General-purpose tag: <eval>
                   2110: 
                   2111: The <eval> tag will be evaluated as a subroutine call passed in the
                   2112: current helper object and state hash as described in <condition> above,
                   2113: but is expected to return a string to be printed directly to the
                   2114: screen. This is useful for dynamically generating messages. 
                   2115: 
                   2116: =cut
                   2117: 
                   2118: # This is basically a type of message.
                   2119: # Programmatically setting $paramHash->{NEXTSTATE} would work, though
                   2120: # it's probably bad form.
                   2121: 
                   2122: sub start_eval {
                   2123:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2124: 
                   2125:     if ($target ne 'helper') {
                   2126:         return '';
                   2127:     }
                   2128:     
                   2129:     my $program = Apache::lonxml::get_all_text('/eval', $parser);
                   2130:     $program = eval('sub { my $helper = shift; my $state = shift; '
                   2131:         . $program . '}');
                   2132:     die 'Error in eval code, Perl said: ' . $@ if $@;
                   2133:     $paramHash->{MESSAGE_TEXT} = &$program($helper, $paramHash);
                   2134: }
                   2135: 
                   2136: sub end_eval { 
                   2137:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2138: 
                   2139:     if ($target ne 'helper') {
                   2140:         return '';
                   2141:     }
                   2142: 
                   2143:     Apache::lonhelper::message->new();
                   2144: }
                   2145: 
1.13      bowersj2 2146: 1;
                   2147: 
                   2148: package Apache::lonhelper::parmwizfinal;
                   2149: 
                   2150: # This is the final state for the parmwizard. It is not generally useful,
                   2151: # so it is not perldoc'ed. It does its own processing.
                   2152: # It is represented with <parmwizfinal />, and
                   2153: # should later be moved to lonparmset.pm .
                   2154: 
                   2155: no strict;
                   2156: @ISA = ('Apache::lonhelper::element');
                   2157: use strict;
1.11      bowersj2 2158: 
1.13      bowersj2 2159: BEGIN {
                   2160:     &Apache::lonhelper::register('Apache::lonhelper::parmwizfinal',
                   2161:                                  ('parmwizfinal'));
                   2162: }
                   2163: 
                   2164: use Time::localtime;
                   2165: 
                   2166: sub new {
                   2167:     my $ref = Apache::lonhelper::choices->new();
                   2168:     bless ($ref);
                   2169: }
                   2170: 
                   2171: sub start_parmwizfinal { return ''; }
                   2172: 
                   2173: sub end_parmwizfinal {
                   2174:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2175: 
                   2176:     if ($target ne 'helper') {
                   2177:         return '';
                   2178:     }
                   2179:     Apache::lonhelper::parmwizfinal->new();
                   2180: }
                   2181: 
                   2182: # Renders a form that, when submitted, will form the input to lonparmset.pm
                   2183: sub render {
                   2184:     my $self = shift;
                   2185:     my $vars = $helper->{VARS};
                   2186: 
                   2187:     # FIXME: Unify my designators with the standard ones
                   2188:     my %dateTypeHash = ('open_date' => "Opening Date",
                   2189:                         'due_date' => "Due Date",
                   2190:                         'answer_date' => "Answer Date");
                   2191:     my %parmTypeHash = ('open_date' => "0_opendate",
                   2192:                         'due_date' => "0_duedate",
                   2193:                         'answer_date' => "0_answerdate");
                   2194:     
1.14      bowersj2 2195:     my $result = "<form name='helpform' method='get' action='/adm/parmset'>\n";
1.13      bowersj2 2196:     $result .= '<p>Confirm that this information is correct, then click &quot;Finish Wizard&quot; to complete setting the parameter.<ul>';
                   2197:     my $affectedResourceId = "";
                   2198:     my $parm_name = $parmTypeHash{$vars->{ACTION_TYPE}};
                   2199:     my $level = "";
                   2200:     
                   2201:     # Print the type of manipulation:
                   2202:     $result .= '<li>Setting the <b>' . $dateTypeHash{$vars->{ACTION_TYPE}}
                   2203:                . "</b></li>\n";
                   2204:     if ($vars->{ACTION_TYPE} eq 'due_date' || 
                   2205:         $vars->{ACTION_TYPE} eq 'answer_date') {
                   2206:         # for due dates, we default to "date end" type entries
                   2207:         $result .= "<input type='hidden' name='recent_date_end' " .
                   2208:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2209:         $result .= "<input type='hidden' name='pres_value' " . 
                   2210:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2211:         $result .= "<input type='hidden' name='pres_type' " .
                   2212:             "value='date_end' />\n";
                   2213:     } elsif ($vars->{ACTION_TYPE} eq 'open_date') {
                   2214:         $result .= "<input type='hidden' name='recent_date_start' ".
                   2215:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2216:         $result .= "<input type='hidden' name='pres_value' " .
                   2217:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2218:         $result .= "<input type='hidden' name='pres_type' " .
                   2219:             "value='date_start' />\n";
                   2220:     } 
                   2221:     
                   2222:     # Print the granularity, depending on the action
                   2223:     if ($vars->{GRANULARITY} eq 'whole_course') {
                   2224:         $result .= '<li>for <b>all resources in the course</b></li>';
                   2225:         $level = 9; # general course, see lonparmset.pm perldoc
                   2226:         $affectedResourceId = "0.0";
                   2227:     } elsif ($vars->{GRANULARITY} eq 'map') {
                   2228:         my $navmap = Apache::lonnavmaps::navmap->new(
                   2229:                            $ENV{"request.course.fn"}.".db",
                   2230:                            $ENV{"request.course.fn"}."_parms.db", 0, 0);
                   2231:         my $res = $navmap->getById($vars->{RESOURCE_ID});
                   2232:         my $title = $res->compTitle();
                   2233:         $navmap->untieHashes();
                   2234:         $result .= "<li>for the map named <b>$title</b></li>";
                   2235:         $level = 8;
                   2236:         $affectedResourceId = $vars->{RESOURCE_ID};
                   2237:     } else {
                   2238:         my $navmap = Apache::lonnavmaps::navmap->new(
                   2239:                            $ENV{"request.course.fn"}.".db",
                   2240:                            $ENV{"request.course.fn"}."_parms.db", 0, 0);
                   2241:         my $res = $navmap->getById($vars->{RESOURCE_ID});
                   2242:         my $title = $res->compTitle();
                   2243:         $navmap->untieHashes();
                   2244:         $result .= "<li>for the resource named <b>$title</b></li>";
                   2245:         $level = 7;
                   2246:         $affectedResourceId = $vars->{RESOURCE_ID};
                   2247:     }
                   2248: 
                   2249:     # Print targets
                   2250:     if ($vars->{TARGETS} eq 'course') {
                   2251:         $result .= '<li>for <b>all students in course</b></li>';
                   2252:     } elsif ($vars->{TARGETS} eq 'section') {
                   2253:         my $section = $vars->{SECTION_NAME};
                   2254:         $result .= "<li>for section <b>$section</b></li>";
                   2255:         $level -= 3;
                   2256:         $result .= "<input type='hidden' name='csec' value='" .
                   2257:             HTML::Entities::encode($section) . "' />\n";
                   2258:     } else {
                   2259:         # FIXME: This is probably wasteful! Store the name!
                   2260:         my $classlist = Apache::loncoursedata::get_classlist();
                   2261:         my $name = $classlist->{$vars->{USER_NAME}}->[6];
                   2262:         $result .= "<li>for <b>$name</b></li>";
                   2263:         $level -= 6;
                   2264:         my ($uname, $udom) = split /:/, $vars->{USER_NAME};
                   2265:         $result .= "<input type='hidden' name='uname' value='".
                   2266:             HTML::Entities::encode($uname) . "' />\n";
                   2267:         $result .= "<input type='hidden' name='udom' value='".
                   2268:             HTML::Entities::encode($udom) . "' />\n";
                   2269:     }
                   2270: 
                   2271:     # Print value
                   2272:     $result .= "<li>to <b>" . ctime($vars->{PARM_DATE}) . "</b> (" .
                   2273:         Apache::lonnavmaps::timeToHumanString($vars->{PARM_DATE}) 
                   2274:         . ")</li>\n";
                   2275: 
                   2276:     # print pres_marker
                   2277:     $result .= "\n<input type='hidden' name='pres_marker'" .
                   2278:         " value='$affectedResourceId&$parm_name&$level' />\n";
                   2279: 
                   2280:     $result .= "<br /><br /><center><input type='submit' value='Finish Helper' /></center></form>\n";
                   2281: 
                   2282:     return $result;
                   2283: }
                   2284:     
                   2285: sub overrideForm {
                   2286:     return 1;
                   2287: }
1.5       bowersj2 2288: 
1.4       bowersj2 2289: 1;
1.3       bowersj2 2290: 
1.1       bowersj2 2291: __END__
1.3       bowersj2 2292: 

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