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

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

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