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

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) {
1.15      bowersj2  991: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
                    992:             document.forms.helpform.elements[i].checked=value;
1.5       bowersj2  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.16    ! bowersj2 1005:     if (defined $self->{ERROR_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: 
1.15      bowersj2 1458:     my $buttons = '';
                   1459: 
                   1460:     if ($self->{'multichoice'}) {
                   1461:         $result = <<SCRIPT;
                   1462: <script>
                   1463:     function checkall(value) {
                   1464: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
                   1465:             ele = document.forms.helpform.elements[i];
                   1466:             if (ele.type == "checkbox") {
                   1467:                 document.forms.helpform.elements[i].checked=value;
                   1468:             }
                   1469:         }
                   1470:     }
                   1471: </script>
                   1472: SCRIPT
                   1473:         $buttons = <<BUTTONS;
                   1474: <br /> &nbsp;
                   1475: <input type="button" onclick="checkall(true)" value="Select All" />
                   1476: <input type="button" onclick="checkall(false)" value="Unselect All" />
                   1477: <br /> &nbsp;
                   1478: BUTTONS
                   1479:     }
                   1480: 
1.5       bowersj2 1481:     if (defined $self->{ERROR_MSG}) {
1.14      bowersj2 1482:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
1.5       bowersj2 1483:     }
                   1484: 
1.15      bowersj2 1485:     $result .= $buttons;
                   1486: 
1.5       bowersj2 1487:     my $filterFunc = $self->{FILTER_FUNC};
                   1488:     my $choiceFunc = $self->{CHOICE_FUNC};
                   1489:     my $valueFunc = $self->{VALUE_FUNC};
1.13      bowersj2 1490:     my $mapUrl = $self->{MAP_URL};
1.14      bowersj2 1491:     my $multichoice = $self->{'multichoice'};
1.5       bowersj2 1492: 
                   1493:     # Create the composite function that renders the column on the nav map
                   1494:     # have to admit any language that lets me do this can't be all bad
                   1495:     #  - Jeremy (Pythonista) ;-)
                   1496:     my $checked = 0;
                   1497:     my $renderColFunc = sub {
                   1498:         my ($resource, $part, $params) = @_;
1.14      bowersj2 1499: 
                   1500:         my $inputType;
                   1501:         if ($multichoice) { $inputType = 'checkbox'; }
                   1502:         else {$inputType = 'radio'; }
                   1503: 
1.5       bowersj2 1504:         if (!&$choiceFunc($resource)) {
                   1505:             return '<td>&nbsp;</td>';
                   1506:         } else {
1.14      bowersj2 1507:             my $col = "<td><input type='$inputType' name='${var}.forminput' ";
                   1508:             if (!$checked && !$multichoice) {
1.5       bowersj2 1509:                 $col .= "checked ";
                   1510:                 $checked = 1;
                   1511:             }
                   1512:             $col .= "value='" . 
                   1513:                 HTML::Entities::encode(&$valueFunc($resource)) 
                   1514:                 . "' /></td>";
                   1515:             return $col;
                   1516:         }
                   1517:     };
                   1518: 
                   1519:     $ENV{'form.condition'} = 1;
                   1520:     $result .= 
                   1521:         &Apache::lonnavmaps::render( { 'cols' => [$renderColFunc, 
                   1522:                                                   Apache::lonnavmaps::resource()],
                   1523:                                        'showParts' => 0,
                   1524:                                        'filterFunc' => $filterFunc,
1.13      bowersj2 1525:                                        'resource_no_folder_link' => 1,
                   1526:                                        'iterator_map' => $mapUrl }
1.5       bowersj2 1527:                                        );
1.15      bowersj2 1528: 
                   1529:     $result .= $buttons;
1.5       bowersj2 1530:                                                 
                   1531:     return $result;
                   1532: }
                   1533:     
                   1534: sub postprocess {
                   1535:     my $self = shift;
1.14      bowersj2 1536: 
                   1537:     if ($self->{'multichoice'}) {
                   1538:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
                   1539:                                         $self->{'variable'});
                   1540:     }
                   1541: 
                   1542:     if ($self->{'multichoice'} && !$helper->{VARS}->{$self->{'variable'}}) {
                   1543:         $self->{ERROR_MSG} = 'You must choose at least one resource to continue.';
                   1544:         return 0;
                   1545:     }
                   1546: 
1.5       bowersj2 1547:     if (defined($self->{NEXTSTATE})) {
                   1548:         $helper->changeState($self->{NEXTSTATE});
                   1549:     }
1.6       bowersj2 1550: 
                   1551:     return 1;
1.5       bowersj2 1552: }
                   1553: 
                   1554: 1;
                   1555: 
                   1556: package Apache::lonhelper::student;
                   1557: 
                   1558: =pod
                   1559: 
                   1560: =head2 Element: student
                   1561: 
                   1562: Student elements display a choice of students enrolled in the current
                   1563: course. Currently it is primitive; this is expected to evolve later.
                   1564: 
                   1565: Student elements take two attributes: "variable", which means what
                   1566: it usually does, and "multichoice", which if true allows the user
                   1567: to select multiple students.
                   1568: 
                   1569: =cut
                   1570: 
                   1571: no strict;
                   1572: @ISA = ("Apache::lonhelper::element");
                   1573: use strict;
                   1574: 
                   1575: 
                   1576: 
                   1577: BEGIN {
1.7       bowersj2 1578:     &Apache::lonhelper::register('Apache::lonhelper::student',
1.5       bowersj2 1579:                               ('student'));
                   1580: }
                   1581: 
                   1582: sub new {
                   1583:     my $ref = Apache::lonhelper::element->new();
                   1584:     bless($ref);
                   1585: }
1.4       bowersj2 1586: 
1.5       bowersj2 1587: sub start_student {
1.4       bowersj2 1588:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1589: 
                   1590:     if ($target ne 'helper') {
                   1591:         return '';
                   1592:     }
                   1593: 
1.5       bowersj2 1594:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1595:     $helper->declareVar($paramHash->{'variable'});
                   1596:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.12      bowersj2 1597:     if (defined($token->[2]{'nextstate'})) {
                   1598:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
                   1599:     }
                   1600:     
1.5       bowersj2 1601: }    
                   1602: 
                   1603: sub end_student {
                   1604:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1605: 
                   1606:     if ($target ne 'helper') {
                   1607:         return '';
                   1608:     }
                   1609:     Apache::lonhelper::student->new();
1.3       bowersj2 1610: }
1.5       bowersj2 1611: 
                   1612: sub render {
                   1613:     my $self = shift;
                   1614:     my $result = '';
                   1615:     my $buttons = '';
                   1616: 
                   1617:     if ($self->{'multichoice'}) {
                   1618:         $result = <<SCRIPT;
                   1619: <script>
                   1620:     function checkall(value) {
1.15      bowersj2 1621: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
                   1622:             document.forms.helpform.elements[i].checked=value;
1.5       bowersj2 1623:         }
                   1624:     }
                   1625: </script>
                   1626: SCRIPT
                   1627:         $buttons = <<BUTTONS;
                   1628: <br />
                   1629: <input type="button" onclick="checkall(true)" value="Select All" />
                   1630: <input type="button" onclick="checkall(false)" value="Unselect All" />
                   1631: <br />
                   1632: BUTTONS
                   1633:     }
                   1634: 
                   1635:     if (defined $self->{ERROR_MSG}) {
                   1636:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   1637:     }
                   1638: 
                   1639:     # Load up the students
                   1640:     my $choices = &Apache::loncoursedata::get_classlist();
                   1641:     my @keys = keys %{$choices};
                   1642: 
                   1643:     # Constants
                   1644:     my $section = Apache::loncoursedata::CL_SECTION();
                   1645:     my $fullname = Apache::loncoursedata::CL_FULLNAME();
                   1646: 
                   1647:     # Sort by: Section, name
                   1648:     @keys = sort {
                   1649:         if ($choices->{$a}->[$section] ne $choices->{$b}->[$section]) {
                   1650:             return $choices->{$a}->[$section] cmp $choices->{$b}->[$section];
                   1651:         }
                   1652:         return $choices->{$a}->[$fullname] cmp $choices->{$b}->[$fullname];
                   1653:     } @keys;
                   1654: 
                   1655:     my $type = 'radio';
                   1656:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
                   1657:     $result .= "<table cellspacing='2' cellpadding='2' border='0'>\n";
                   1658:     $result .= "<tr><td></td><td align='center'><b>Student Name</b></td>".
                   1659:         "<td align='center'><b>Section</b></td></tr>";
                   1660: 
                   1661:     my $checked = 0;
                   1662:     foreach (@keys) {
                   1663:         $result .= "<tr><td><input type='$type' name='" .
                   1664:             $self->{'variable'} . '.forminput' . "'";
                   1665:             
                   1666:         if (!$self->{'multichoice'} && !$checked) {
                   1667:             $result .= " checked ";
                   1668:             $checked = 1;
                   1669:         }
                   1670:         $result .=
                   1671:             " value='" . HTML::Entities::encode($_)
                   1672:             . "' /></td><td>"
                   1673:             . HTML::Entities::encode($choices->{$_}->[$fullname])
                   1674:             . "</td><td align='center'>" 
                   1675:             . HTML::Entities::encode($choices->{$_}->[$section])
                   1676:             . "</td></tr>\n";
                   1677:     }
                   1678: 
                   1679:     $result .= "</table>\n\n";
                   1680:     $result .= $buttons;    
1.4       bowersj2 1681:     
1.5       bowersj2 1682:     return $result;
                   1683: }
                   1684: 
1.6       bowersj2 1685: sub postprocess {
                   1686:     my $self = shift;
                   1687: 
                   1688:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
                   1689:     if (!$result) {
                   1690:         $self->{ERROR_MSG} = 'You must choose at least one student '.
                   1691:             'to continue.';
                   1692:         return 0;
                   1693:     }
                   1694: 
                   1695:     if ($self->{'multichoice'}) {
                   1696:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
                   1697:                                         $self->{'variable'});
                   1698:     }
                   1699:     if (defined($self->{NEXTSTATE})) {
                   1700:         $helper->changeState($self->{NEXTSTATE});
                   1701:     }
                   1702: 
                   1703:     return 1;
                   1704: }
                   1705: 
1.5       bowersj2 1706: 1;
                   1707: 
                   1708: package Apache::lonhelper::files;
                   1709: 
                   1710: =pod
                   1711: 
                   1712: =head2 Element: files
                   1713: 
                   1714: files allows the users to choose files from a given directory on the
                   1715: server. It is always multichoice and stores the result as a triple-pipe
                   1716: delimited entry in the helper variables. 
                   1717: 
                   1718: Since it is extremely unlikely that you can actually code a constant
                   1719: representing the directory you wish to allow the user to search, <files>
                   1720: takes a subroutine that returns the name of the directory you wish to
                   1721: have the user browse.
                   1722: 
                   1723: files accepts the attribute "variable" to control where the files chosen
                   1724: are put. It accepts the attribute "multichoice" as the other attribute,
                   1725: defaulting to false, which if true will allow the user to select more
                   1726: then one choice. 
                   1727: 
                   1728: <files> accepts three subtags. One is the "nextstate" sub-tag that works
                   1729: as it does with the other tags. Another is a <filechoice> sub tag that
                   1730: is Perl code that, when surrounded by "sub {" and "}" will return a
                   1731: string representing what directory on the server to allow the user to 
                   1732: choose files from. Finally, the <filefilter> subtag should contain Perl
                   1733: code that when surrounded by "sub { my $filename = shift; " and "}",
                   1734: returns a true value if the user can pick that file, or false otherwise.
                   1735: The filename passed to the function will be just the name of the file, 
                   1736: with no path info.
                   1737: 
                   1738: =cut
                   1739: 
                   1740: no strict;
                   1741: @ISA = ("Apache::lonhelper::element");
                   1742: use strict;
                   1743: 
                   1744: BEGIN {
1.7       bowersj2 1745:     &Apache::lonhelper::register('Apache::lonhelper::files',
                   1746:                                  ('files', 'filechoice', 'filefilter'));
1.5       bowersj2 1747: }
                   1748: 
                   1749: sub new {
                   1750:     my $ref = Apache::lonhelper::element->new();
                   1751:     bless($ref);
                   1752: }
                   1753: 
                   1754: sub start_files {
                   1755:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1756: 
                   1757:     if ($target ne 'helper') {
                   1758:         return '';
                   1759:     }
                   1760:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1761:     $helper->declareVar($paramHash->{'variable'});
                   1762:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
                   1763: }    
                   1764: 
                   1765: sub end_files {
                   1766:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1767: 
                   1768:     if ($target ne 'helper') {
                   1769:         return '';
                   1770:     }
                   1771:     if (!defined($paramHash->{FILTER_FUNC})) {
                   1772:         $paramHash->{FILTER_FUNC} = sub { return 1; };
                   1773:     }
                   1774:     Apache::lonhelper::files->new();
                   1775: }    
                   1776: 
                   1777: sub start_filechoice {
                   1778:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1779: 
                   1780:     if ($target ne 'helper') {
                   1781:         return '';
                   1782:     }
                   1783:     $paramHash->{'filechoice'} = Apache::lonxml::get_all_text('/filechoice',
                   1784:                                                               $parser);
                   1785: }
                   1786: 
                   1787: sub end_filechoice { return ''; }
                   1788: 
                   1789: sub start_filefilter {
                   1790:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1791: 
                   1792:     if ($target ne 'helper') {
                   1793:         return '';
                   1794:     }
                   1795: 
                   1796:     my $contents = Apache::lonxml::get_all_text('/filefilter',
                   1797:                                                 $parser);
                   1798:     $contents = 'sub { my $filename = shift; ' . $contents . '}';
                   1799:     $paramHash->{FILTER_FUNC} = eval $contents;
                   1800: }
                   1801: 
                   1802: sub end_filefilter { return ''; }
1.3       bowersj2 1803: 
                   1804: sub render {
                   1805:     my $self = shift;
1.5       bowersj2 1806:     my $result = '';
                   1807:     my $var = $self->{'variable'};
                   1808:     
                   1809:     my $subdirFunc = eval('sub {' . $self->{'filechoice'} . '}');
1.11      bowersj2 1810:     die 'Error in resource filter code for variable ' . 
                   1811:         {'variable'} . ', Perl said:' . $@ if $@;
                   1812: 
1.5       bowersj2 1813:     my $subdir = &$subdirFunc();
                   1814: 
                   1815:     my $filterFunc = $self->{FILTER_FUNC};
                   1816:     my $buttons = '';
                   1817: 
                   1818:     if ($self->{'multichoice'}) {
                   1819:         $result = <<SCRIPT;
                   1820: <script>
                   1821:     function checkall(value) {
1.15      bowersj2 1822: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
                   1823:             ele = document.forms.helpform.elements[i];
1.5       bowersj2 1824:             if (ele.type == "checkbox") {
1.15      bowersj2 1825:                 document.forms.helpform.elements[i].checked=value;
1.5       bowersj2 1826:             }
                   1827:         }
                   1828:     }
                   1829: </script>
                   1830: SCRIPT
1.15      bowersj2 1831:         $buttons = <<BUTTONS;
1.5       bowersj2 1832: <br /> &nbsp;
                   1833: <input type="button" onclick="checkall(true)" value="Select All" />
                   1834: <input type="button" onclick="checkall(false)" value="Unselect All" />
                   1835: <br /> &nbsp;
                   1836: BUTTONS
                   1837:     }
                   1838: 
                   1839:     # Get the list of files in this directory.
                   1840:     my @fileList;
                   1841: 
                   1842:     # If the subdirectory is in local CSTR space
                   1843:     if ($subdir =~ m|/home/([^/]+)/public_html|) {
                   1844:         my $user = $1;
                   1845:         my $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
                   1846:         @fileList = &Apache::lonnet::dirlist($subdir, $domain, $user, '');
                   1847:     } else {
                   1848:         # local library server resource space
                   1849:         @fileList = &Apache::lonnet::dirlist($subdir, $ENV{'user.domain'}, $ENV{'user.name'}, '');
                   1850:     }
1.3       bowersj2 1851: 
1.5       bowersj2 1852:     $result .= $buttons;
                   1853: 
1.6       bowersj2 1854:     if (defined $self->{ERROR_MSG}) {
                   1855:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   1856:     }
                   1857: 
1.5       bowersj2 1858:     $result .= '<table border="0" cellpadding="1" cellspacing="1">';
                   1859: 
                   1860:     # Keeps track if there are no choices, prints appropriate error
                   1861:     # if there are none. 
                   1862:     my $choices = 0;
                   1863:     my $type = 'radio';
                   1864:     if ($self->{'multichoice'}) {
                   1865:         $type = 'checkbox';
                   1866:     }
                   1867:     # Print each legitimate file choice.
                   1868:     for my $file (@fileList) {
                   1869:         $file = (split(/&/, $file))[0];
                   1870:         if ($file eq '.' || $file eq '..') {
                   1871:             next;
                   1872:         }
                   1873:         my $fileName = $subdir .'/'. $file;
                   1874:         if (&$filterFunc($file)) {
                   1875:             $result .= '<tr><td align="right">' .
                   1876:                 "<input type='$type' name='" . $var
                   1877:             . ".forminput' value='" . HTML::Entities::encode($fileName) .
                   1878:                 "'";
                   1879:             if (!$self->{'multichoice'} && $choices == 0) {
                   1880:                 $result .= ' checked';
                   1881:             }
                   1882:             $result .= "/></td><td>" . $file . "</td></tr>\n";
                   1883:             $choices++;
                   1884:         }
                   1885:     }
                   1886: 
                   1887:     $result .= "</table>\n";
                   1888: 
                   1889:     if (!$choices) {
                   1890:         $result .= '<font color="#FF0000">There are no files available to select in this directory. Please go back and select another option.</font><br /><br />';
                   1891:     }
                   1892: 
                   1893:     $result .= $buttons;
                   1894: 
                   1895:     return $result;
1.4       bowersj2 1896: }
1.5       bowersj2 1897: 
1.4       bowersj2 1898: sub postprocess {
                   1899:     my $self = shift;
1.6       bowersj2 1900:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
                   1901:     if (!$result) {
                   1902:         $self->{ERROR_MSG} = 'You must choose at least one file '.
                   1903:             'to continue.';
                   1904:         return 0;
                   1905:     }
                   1906: 
1.5       bowersj2 1907:     if ($self->{'multichoice'}) {
                   1908:         $self->process_multiple_choices($self->{'variable'}.'.forminput',
                   1909:                                         $self->{'variable'});
                   1910:     }
                   1911:     if (defined($self->{NEXTSTATE})) {
                   1912:         $helper->changeState($self->{NEXTSTATE});
1.3       bowersj2 1913:     }
1.6       bowersj2 1914: 
                   1915:     return 1;
1.3       bowersj2 1916: }
1.8       bowersj2 1917: 
                   1918: 1;
                   1919: 
1.11      bowersj2 1920: package Apache::lonhelper::section;
                   1921: 
                   1922: =pod
                   1923: 
                   1924: =head2 Element: section
                   1925: 
                   1926: <section> allows the user to choose one or more sections from the current
                   1927: course.
                   1928: 
                   1929: It takes the standard attributes "variable", "multichoice", and
                   1930: "nextstate", meaning what they do for most other elements.
                   1931: 
                   1932: =cut
                   1933: 
                   1934: no strict;
                   1935: @ISA = ("Apache::lonhelper::choices");
                   1936: use strict;
                   1937: 
                   1938: BEGIN {
                   1939:     &Apache::lonhelper::register('Apache::lonhelper::section',
                   1940:                                  ('section'));
                   1941: }
                   1942: 
                   1943: sub new {
                   1944:     my $ref = Apache::lonhelper::choices->new();
                   1945:     bless($ref);
                   1946: }
                   1947: 
                   1948: sub start_section {
                   1949:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1950: 
                   1951:     if ($target ne 'helper') {
                   1952:         return '';
                   1953:     }
1.12      bowersj2 1954: 
                   1955:     $paramHash->{CHOICES} = [];
                   1956: 
1.11      bowersj2 1957:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1958:     $helper->declareVar($paramHash->{'variable'});
                   1959:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
                   1960:     if (defined($token->[2]{'nextstate'})) {
1.12      bowersj2 1961:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
1.11      bowersj2 1962:     }
                   1963: 
                   1964:     # Populate the CHOICES element
                   1965:     my %choices;
                   1966: 
                   1967:     my $section = Apache::loncoursedata::CL_SECTION();
                   1968:     my $classlist = Apache::loncoursedata::get_classlist();
                   1969:     foreach (keys %$classlist) {
                   1970:         my $sectionName = $classlist->{$_}->[$section];
                   1971:         if (!$sectionName) {
                   1972:             $choices{"No section assigned"} = "";
                   1973:         } else {
                   1974:             $choices{$sectionName} = $sectionName;
                   1975:         }
1.12      bowersj2 1976:     } 
                   1977:    
1.11      bowersj2 1978:     for my $sectionName (sort(keys(%choices))) {
1.12      bowersj2 1979:         
1.11      bowersj2 1980:         push @{$paramHash->{CHOICES}}, [$sectionName, $sectionName];
                   1981:     }
                   1982: }    
                   1983: 
1.12      bowersj2 1984: sub end_section {
                   1985:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.11      bowersj2 1986: 
1.12      bowersj2 1987:     if ($target ne 'helper') {
                   1988:         return '';
                   1989:     }
                   1990:     Apache::lonhelper::section->new();
                   1991: }    
1.11      bowersj2 1992: 1;
                   1993: 
1.8       bowersj2 1994: package Apache::lonhelper::general;
                   1995: 
                   1996: =pod
                   1997: 
                   1998: =head2 General-purpose tag: <exec>
                   1999: 
                   2000: The contents of the exec tag are executed as Perl code, not inside a 
                   2001: safe space, so the full range of $ENV and such is available. The code
                   2002: will be executed as a subroutine wrapped with the following code:
                   2003: 
                   2004: "sub { my $helper = shift; my $state = shift;" and
                   2005: 
                   2006: "}"
                   2007: 
                   2008: The return value is ignored.
                   2009: 
                   2010: $helper is the helper object. Feel free to add methods to the helper
                   2011: object to support whatever manipulation you may need to do (for instance,
                   2012: overriding the form location if the state is the final state; see 
                   2013: lonparm.helper for an example).
                   2014: 
                   2015: $state is the $paramHash that has currently been generated and may
                   2016: be manipulated by the code in exec. Note that the $state is not yet
                   2017: an actual state B<object>, it is just a hash, so do not expect to
                   2018: be able to call methods on it.
                   2019: 
                   2020: =cut
                   2021: 
                   2022: BEGIN {
                   2023:     &Apache::lonhelper::register('Apache::lonhelper::general',
1.11      bowersj2 2024:                                  'exec', 'condition', 'clause',
                   2025:                                  'eval');
1.8       bowersj2 2026: }
                   2027: 
                   2028: sub start_exec {
                   2029:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2030: 
                   2031:     if ($target ne 'helper') {
                   2032:         return '';
                   2033:     }
                   2034:     
                   2035:     my $code = &Apache::lonxml::get_all_text('/exec', $parser);
                   2036:     
                   2037:     $code = eval ('sub { my $helper = shift; my $state = shift; ' .
                   2038:         $code . "}");
1.11      bowersj2 2039:     die 'Error in <exec>, Perl said: '. $@ if $@;
1.8       bowersj2 2040:     &$code($helper, $paramHash);
                   2041: }
                   2042: 
                   2043: sub end_exec { return ''; }
                   2044: 
                   2045: =pod
                   2046: 
                   2047: =head2 General-purpose tag: <condition>
                   2048: 
                   2049: The <condition> tag allows you to mask out parts of the helper code
                   2050: depending on some programatically determined condition. The condition
                   2051: tag contains a tag <clause> which contains perl code that when wrapped
                   2052: with "sub { my $helper = shift; my $state = shift; " and "}", returns
                   2053: a true value if the XML in the condition should be evaluated as a normal
                   2054: part of the helper, or false if it should be completely discarded.
                   2055: 
                   2056: The <clause> tag must be the first sub-tag of the <condition> tag or
                   2057: it will not work as expected.
                   2058: 
                   2059: =cut
                   2060: 
                   2061: # The condition tag just functions as a marker, it doesn't have
                   2062: # to "do" anything. Technically it doesn't even have to be registered
                   2063: # with the lonxml code, but I leave this here to be explicit about it.
                   2064: sub start_condition { return ''; }
                   2065: sub end_condition { return ''; }
                   2066: 
                   2067: sub start_clause {
                   2068:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2069: 
                   2070:     if ($target ne 'helper') {
                   2071:         return '';
                   2072:     }
                   2073:     
                   2074:     my $clause = Apache::lonxml::get_all_text('/clause', $parser);
                   2075:     $clause = eval('sub { my $helper = shift; my $state = shift; '
                   2076:         . $clause . '}');
1.11      bowersj2 2077:     die 'Error in clause of condition, Perl said: ' . $@ if $@;
1.8       bowersj2 2078:     if (!&$clause($helper, $paramHash)) {
                   2079:         # Discard all text until the /condition.
                   2080:         &Apache::lonxml::get_all_text('/condition', $parser);
                   2081:     }
                   2082: }
                   2083: 
                   2084: sub end_clause { return ''; }
1.11      bowersj2 2085: 
                   2086: =pod
                   2087: 
                   2088: =head2 General-purpose tag: <eval>
                   2089: 
                   2090: The <eval> tag will be evaluated as a subroutine call passed in the
                   2091: current helper object and state hash as described in <condition> above,
                   2092: but is expected to return a string to be printed directly to the
                   2093: screen. This is useful for dynamically generating messages. 
                   2094: 
                   2095: =cut
                   2096: 
                   2097: # This is basically a type of message.
                   2098: # Programmatically setting $paramHash->{NEXTSTATE} would work, though
                   2099: # it's probably bad form.
                   2100: 
                   2101: sub start_eval {
                   2102:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2103: 
                   2104:     if ($target ne 'helper') {
                   2105:         return '';
                   2106:     }
                   2107:     
                   2108:     my $program = Apache::lonxml::get_all_text('/eval', $parser);
                   2109:     $program = eval('sub { my $helper = shift; my $state = shift; '
                   2110:         . $program . '}');
                   2111:     die 'Error in eval code, Perl said: ' . $@ if $@;
                   2112:     $paramHash->{MESSAGE_TEXT} = &$program($helper, $paramHash);
                   2113: }
                   2114: 
                   2115: sub end_eval { 
                   2116:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2117: 
                   2118:     if ($target ne 'helper') {
                   2119:         return '';
                   2120:     }
                   2121: 
                   2122:     Apache::lonhelper::message->new();
                   2123: }
                   2124: 
1.13      bowersj2 2125: 1;
                   2126: 
                   2127: package Apache::lonhelper::parmwizfinal;
                   2128: 
                   2129: # This is the final state for the parmwizard. It is not generally useful,
                   2130: # so it is not perldoc'ed. It does its own processing.
                   2131: # It is represented with <parmwizfinal />, and
                   2132: # should later be moved to lonparmset.pm .
                   2133: 
                   2134: no strict;
                   2135: @ISA = ('Apache::lonhelper::element');
                   2136: use strict;
1.11      bowersj2 2137: 
1.13      bowersj2 2138: BEGIN {
                   2139:     &Apache::lonhelper::register('Apache::lonhelper::parmwizfinal',
                   2140:                                  ('parmwizfinal'));
                   2141: }
                   2142: 
                   2143: use Time::localtime;
                   2144: 
                   2145: sub new {
                   2146:     my $ref = Apache::lonhelper::choices->new();
                   2147:     bless ($ref);
                   2148: }
                   2149: 
                   2150: sub start_parmwizfinal { return ''; }
                   2151: 
                   2152: sub end_parmwizfinal {
                   2153:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2154: 
                   2155:     if ($target ne 'helper') {
                   2156:         return '';
                   2157:     }
                   2158:     Apache::lonhelper::parmwizfinal->new();
                   2159: }
                   2160: 
                   2161: # Renders a form that, when submitted, will form the input to lonparmset.pm
                   2162: sub render {
                   2163:     my $self = shift;
                   2164:     my $vars = $helper->{VARS};
                   2165: 
                   2166:     # FIXME: Unify my designators with the standard ones
                   2167:     my %dateTypeHash = ('open_date' => "Opening Date",
                   2168:                         'due_date' => "Due Date",
                   2169:                         'answer_date' => "Answer Date");
                   2170:     my %parmTypeHash = ('open_date' => "0_opendate",
                   2171:                         'due_date' => "0_duedate",
                   2172:                         'answer_date' => "0_answerdate");
                   2173:     
1.14      bowersj2 2174:     my $result = "<form name='helpform' method='get' action='/adm/parmset'>\n";
1.13      bowersj2 2175:     $result .= '<p>Confirm that this information is correct, then click &quot;Finish Wizard&quot; to complete setting the parameter.<ul>';
                   2176:     my $affectedResourceId = "";
                   2177:     my $parm_name = $parmTypeHash{$vars->{ACTION_TYPE}};
                   2178:     my $level = "";
                   2179:     
                   2180:     # Print the type of manipulation:
                   2181:     $result .= '<li>Setting the <b>' . $dateTypeHash{$vars->{ACTION_TYPE}}
                   2182:                . "</b></li>\n";
                   2183:     if ($vars->{ACTION_TYPE} eq 'due_date' || 
                   2184:         $vars->{ACTION_TYPE} eq 'answer_date') {
                   2185:         # for due dates, we default to "date end" type entries
                   2186:         $result .= "<input type='hidden' name='recent_date_end' " .
                   2187:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2188:         $result .= "<input type='hidden' name='pres_value' " . 
                   2189:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2190:         $result .= "<input type='hidden' name='pres_type' " .
                   2191:             "value='date_end' />\n";
                   2192:     } elsif ($vars->{ACTION_TYPE} eq 'open_date') {
                   2193:         $result .= "<input type='hidden' name='recent_date_start' ".
                   2194:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2195:         $result .= "<input type='hidden' name='pres_value' " .
                   2196:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2197:         $result .= "<input type='hidden' name='pres_type' " .
                   2198:             "value='date_start' />\n";
                   2199:     } 
                   2200:     
                   2201:     # Print the granularity, depending on the action
                   2202:     if ($vars->{GRANULARITY} eq 'whole_course') {
                   2203:         $result .= '<li>for <b>all resources in the course</b></li>';
                   2204:         $level = 9; # general course, see lonparmset.pm perldoc
                   2205:         $affectedResourceId = "0.0";
                   2206:     } elsif ($vars->{GRANULARITY} eq 'map') {
                   2207:         my $navmap = Apache::lonnavmaps::navmap->new(
                   2208:                            $ENV{"request.course.fn"}.".db",
                   2209:                            $ENV{"request.course.fn"}."_parms.db", 0, 0);
                   2210:         my $res = $navmap->getById($vars->{RESOURCE_ID});
                   2211:         my $title = $res->compTitle();
                   2212:         $navmap->untieHashes();
                   2213:         $result .= "<li>for the map named <b>$title</b></li>";
                   2214:         $level = 8;
                   2215:         $affectedResourceId = $vars->{RESOURCE_ID};
                   2216:     } else {
                   2217:         my $navmap = Apache::lonnavmaps::navmap->new(
                   2218:                            $ENV{"request.course.fn"}.".db",
                   2219:                            $ENV{"request.course.fn"}."_parms.db", 0, 0);
                   2220:         my $res = $navmap->getById($vars->{RESOURCE_ID});
                   2221:         my $title = $res->compTitle();
                   2222:         $navmap->untieHashes();
                   2223:         $result .= "<li>for the resource named <b>$title</b></li>";
                   2224:         $level = 7;
                   2225:         $affectedResourceId = $vars->{RESOURCE_ID};
                   2226:     }
                   2227: 
                   2228:     # Print targets
                   2229:     if ($vars->{TARGETS} eq 'course') {
                   2230:         $result .= '<li>for <b>all students in course</b></li>';
                   2231:     } elsif ($vars->{TARGETS} eq 'section') {
                   2232:         my $section = $vars->{SECTION_NAME};
                   2233:         $result .= "<li>for section <b>$section</b></li>";
                   2234:         $level -= 3;
                   2235:         $result .= "<input type='hidden' name='csec' value='" .
                   2236:             HTML::Entities::encode($section) . "' />\n";
                   2237:     } else {
                   2238:         # FIXME: This is probably wasteful! Store the name!
                   2239:         my $classlist = Apache::loncoursedata::get_classlist();
                   2240:         my $name = $classlist->{$vars->{USER_NAME}}->[6];
                   2241:         $result .= "<li>for <b>$name</b></li>";
                   2242:         $level -= 6;
                   2243:         my ($uname, $udom) = split /:/, $vars->{USER_NAME};
                   2244:         $result .= "<input type='hidden' name='uname' value='".
                   2245:             HTML::Entities::encode($uname) . "' />\n";
                   2246:         $result .= "<input type='hidden' name='udom' value='".
                   2247:             HTML::Entities::encode($udom) . "' />\n";
                   2248:     }
                   2249: 
                   2250:     # Print value
                   2251:     $result .= "<li>to <b>" . ctime($vars->{PARM_DATE}) . "</b> (" .
                   2252:         Apache::lonnavmaps::timeToHumanString($vars->{PARM_DATE}) 
                   2253:         . ")</li>\n";
                   2254: 
                   2255:     # print pres_marker
                   2256:     $result .= "\n<input type='hidden' name='pres_marker'" .
                   2257:         " value='$affectedResourceId&$parm_name&$level' />\n";
                   2258: 
                   2259:     $result .= "<br /><br /><center><input type='submit' value='Finish Helper' /></center></form>\n";
                   2260: 
                   2261:     return $result;
                   2262: }
                   2263:     
                   2264: sub overrideForm {
                   2265:     return 1;
                   2266: }
1.5       bowersj2 2267: 
1.4       bowersj2 2268: 1;
1.3       bowersj2 2269: 
1.1       bowersj2 2270: __END__
1.3       bowersj2 2271: 

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