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

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

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