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

1.1       bowersj2    1: # The LearningOnline Network with CAPA
                      2: # .helper XML handler to implement the LON-CAPA helper
                      3: #
1.32    ! bowersj2    4: # $Id: lonhelper.pm,v 1.31 2003/05/16 17:20:51 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});
                    639: 
                    640:     return $result;
                    641: }
                    642: 
                    643: 1;
                    644: 
                    645: package Apache::lonhelper::state;
                    646: 
                    647: # States bundle things together and are responsible for compositing the
1.4       bowersj2  648: # various elements together. It is not generally necessary for users to
                    649: # use the state object directly, so it is not perldoc'ed.
                    650: 
                    651: # Basically, all the states do is pass calls to the elements and aggregate
                    652: # the results.
1.3       bowersj2  653: 
                    654: sub new {
                    655:     my $proto = shift;
                    656:     my $class = ref($proto) || $proto;
                    657:     my $self = {};
                    658: 
                    659:     $self->{NAME} = shift;
                    660:     $self->{TITLE} = shift;
                    661:     $self->{ELEMENTS} = [];
                    662: 
                    663:     bless($self, $class);
                    664: 
                    665:     $helper->registerState($self);
                    666: 
1.13      bowersj2  667:     $state = $self;
                    668: 
1.3       bowersj2  669:     return $self;
                    670: }
                    671: 
                    672: sub name {
                    673:     my $self = shift;
                    674:     return $self->{NAME};
                    675: }
                    676: 
                    677: sub title {
                    678:     my $self = shift;
                    679:     return $self->{TITLE};
                    680: }
                    681: 
1.4       bowersj2  682: sub preprocess {
                    683:     my $self = shift;
                    684:     for my $element (@{$self->{ELEMENTS}}) {
                    685:         $element->preprocess();
                    686:     }
                    687: }
                    688: 
1.6       bowersj2  689: # FIXME: Document that all postprocesses must return a true value or
                    690: # the state transition will be overridden
1.4       bowersj2  691: sub postprocess {
                    692:     my $self = shift;
1.6       bowersj2  693: 
                    694:     # Save the state so we can roll it back if we need to.
                    695:     my $originalState = $helper->{STATE};
                    696:     my $everythingSuccessful = 1;
                    697: 
1.4       bowersj2  698:     for my $element (@{$self->{ELEMENTS}}) {
1.6       bowersj2  699:         my $result = $element->postprocess();
                    700:         if (!$result) { $everythingSuccessful = 0; }
                    701:     }
                    702: 
                    703:     # If not all the postprocesses were successful, override
                    704:     # any state transitions that may have occurred. It is the
                    705:     # responsibility of the states to make sure they have 
                    706:     # error handling in that case.
                    707:     if (!$everythingSuccessful) {
                    708:         $helper->{STATE} = $originalState;
1.4       bowersj2  709:     }
                    710: }
                    711: 
1.13      bowersj2  712: # Override the form if any element wants to.
                    713: # two elements overriding the form will make a mess, but that should
                    714: # be considered helper author error ;-)
1.4       bowersj2  715: sub overrideForm {
1.13      bowersj2  716:     my $self = shift;
                    717:     for my $element (@{$self->{ELEMENTS}}) {
                    718:         if ($element->overrideForm()) {
                    719:             return 1;
                    720:         }
                    721:     }
1.4       bowersj2  722:     return 0;
                    723: }
                    724: 
                    725: sub addElement {
                    726:     my $self = shift;
                    727:     my $element = shift;
                    728:     
                    729:     push @{$self->{ELEMENTS}}, $element;
                    730: }
                    731: 
                    732: sub render {
                    733:     my $self = shift;
                    734:     my @results = ();
                    735: 
                    736:     for my $element (@{$self->{ELEMENTS}}) {
                    737:         push @results, $element->render();
                    738:     }
1.28      bowersj2  739: 
1.4       bowersj2  740:     return join("\n", @results);
                    741: }
                    742: 
                    743: 1;
                    744: 
                    745: package Apache::lonhelper::element;
                    746: # Support code for elements
                    747: 
                    748: =pod
                    749: 
                    750: =head2 Element Base Class
                    751: 
1.28      bowersj2  752: The Apache::lonhelper::element base class provides support for elements
                    753: and defines some generally useful tags for use in elements.
1.4       bowersj2  754: 
1.25      bowersj2  755: B<finalcode tag>
                    756: 
                    757: Each element can contain a "finalcode" tag that, when the special FINAL
                    758: helper state is used, will be executed, surrounded by "sub { my $helper = shift;"
                    759: and "}". It is expected to return a string describing what it did, which 
                    760: may be an empty string. See course initialization helper for an example. This is
                    761: generally intended for helpers like the course initialization helper, which consist
                    762: of several panels, each of which is performing some sort of bite-sized functionality.
                    763: 
                    764: B<defaultvalue tag>
                    765: 
                    766: Each element that accepts user input can contain a "defaultvalue" tag that,
                    767: when surrounded by "sub { my $helper = shift; my $state = shift; " and "}",
                    768: will form a subroutine that when called will provide a default value for
                    769: the element. How this value is interpreted by the element is specific to
                    770: the element itself, and possibly the settings the element has (such as 
                    771: multichoice vs. single choice for <choices> tags). 
                    772: 
                    773: This is also intended for things like the course initialization wizard, where the
                    774: user is setting various parameters. By correctly grabbing current settings 
                    775: and including them into the helper, it allows the user to come back to the
                    776: helper later and re-execute it, without needing to worry about overwriting
                    777: some setting accidentally.
                    778: 
                    779: Again, see the course initialization helper for examples.
                    780: 
1.31      bowersj2  781: B<getValue method>
                    782: 
                    783: If the element stores the name of the variable in a 'variable' member, which
                    784: the provided ones all do, you can retreive the value of the variable by calling
                    785: this method.
                    786: 
1.4       bowersj2  787: =cut
                    788: 
1.5       bowersj2  789: BEGIN {
1.7       bowersj2  790:     &Apache::lonhelper::register('Apache::lonhelper::element',
1.25      bowersj2  791:                                  ('nextstate', 'finalcode',
                    792:                                   'defaultvalue'));
1.5       bowersj2  793: }
                    794: 
1.4       bowersj2  795: # Because we use the param hash, this is often a sufficent
                    796: # constructor
                    797: sub new {
                    798:     my $proto = shift;
                    799:     my $class = ref($proto) || $proto;
                    800:     my $self = $paramHash;
                    801:     bless($self, $class);
                    802: 
                    803:     $self->{PARAMS} = $paramHash;
                    804:     $self->{STATE} = $state;
                    805:     $state->addElement($self);
                    806:     
                    807:     # Ensure param hash is not reused
                    808:     $paramHash = {};
                    809: 
                    810:     return $self;
                    811: }   
                    812: 
1.5       bowersj2  813: sub start_nextstate {
                    814:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    815: 
                    816:     if ($target ne 'helper') {
                    817:         return '';
                    818:     }
                    819:     
                    820:     $paramHash->{NEXTSTATE} = &Apache::lonxml::get_all_text('/nextstate',
                    821:                                                              $parser);
                    822:     return '';
                    823: }
                    824: 
                    825: sub end_nextstate { return ''; }
                    826: 
1.25      bowersj2  827: sub start_finalcode {
                    828:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    829: 
                    830:     if ($target ne 'helper') {
                    831:         return '';
                    832:     }
                    833:     
                    834:     $paramHash->{FINAL_CODE} = &Apache::lonxml::get_all_text('/finalcode',
                    835:                                                              $parser);
                    836:     return '';
                    837: }
                    838: 
                    839: sub end_finalcode { return ''; }
                    840: 
                    841: sub start_defaultvalue {
                    842:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    843: 
                    844:     if ($target ne 'helper') {
                    845:         return '';
                    846:     }
                    847:     
                    848:     $paramHash->{DEFAULT_VALUE} = &Apache::lonxml::get_all_text('/defaultvalue',
                    849:                                                              $parser);
                    850:     $paramHash->{DEFAULT_VALUE} = 'sub { my $helper = shift; my $state = shift;' .
                    851:         $paramHash->{DEFAULT_VALUE} . '}';
                    852:     return '';
                    853: }
                    854: 
                    855: sub end_defaultvalue { return ''; }
                    856: 
1.4       bowersj2  857: sub preprocess {
                    858:     return 1;
                    859: }
                    860: 
                    861: sub postprocess {
                    862:     return 1;
                    863: }
                    864: 
                    865: sub render {
                    866:     return '';
                    867: }
                    868: 
1.13      bowersj2  869: sub overrideForm {
                    870:     return 0;
                    871: }
                    872: 
1.31      bowersj2  873: sub getValue {
                    874:     my $self = shift;
                    875:     return $helper->{VARS}->{$self->{'variable'}};
                    876: }
                    877: 
1.4       bowersj2  878: 1;
                    879: 
                    880: package Apache::lonhelper::message;
                    881: 
                    882: =pod
                    883: 
                    884: =head2 Element: message
                    885: 
                    886: Message elements display the contents of their <message_text> tags, and
1.5       bowersj2  887: transition directly to the state in the <nextstate> tag. Example:
1.4       bowersj2  888: 
                    889:  <message>
1.5       bowersj2  890:    <nextstate>GET_NAME</nextstate>
1.4       bowersj2  891:    <message_text>This is the <b>message</b> the user will see, 
                    892:                  <i>HTML allowed</i>.</message_text>
                    893:    </message>
                    894: 
1.5       bowersj2  895: This will display the HTML message and transition to the <nextstate> if
1.7       bowersj2  896: given. The HTML will be directly inserted into the helper, so if you don't
1.4       bowersj2  897: want text to run together, you'll need to manually wrap the <message_text>
                    898: in <p> tags, or whatever is appropriate for your HTML.
                    899: 
1.5       bowersj2  900: Message tags do not add in whitespace, so if you want it, you'll need to add
                    901: it into states. This is done so you can inline some elements, such as 
                    902: the <date> element, right between two messages, giving the appearence that 
                    903: the <date> element appears inline. (Note the elements can not be embedded
                    904: within each other.)
                    905: 
1.4       bowersj2  906: This is also a good template for creating your own new states, as it has
                    907: very little code beyond the state template.
                    908: 
                    909: =cut
                    910: 
                    911: no strict;
                    912: @ISA = ("Apache::lonhelper::element");
                    913: use strict;
                    914: 
                    915: BEGIN {
1.7       bowersj2  916:     &Apache::lonhelper::register('Apache::lonhelper::message',
1.10      bowersj2  917:                               ('message'));
1.3       bowersj2  918: }
                    919: 
1.5       bowersj2  920: sub new {
                    921:     my $ref = Apache::lonhelper::element->new();
                    922:     bless($ref);
                    923: }
1.4       bowersj2  924: 
                    925: # CONSTRUCTION: Construct the message element from the XML
                    926: sub start_message {
                    927:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    928: 
                    929:     if ($target ne 'helper') {
                    930:         return '';
                    931:     }
1.10      bowersj2  932: 
                    933:     $paramHash->{MESSAGE_TEXT} = &Apache::lonxml::get_all_text('/message',
                    934:                                                                $parser);
                    935: 
                    936:     if (defined($token->[2]{'nextstate'})) {
                    937:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
                    938:     }
1.4       bowersj2  939:     return '';
1.3       bowersj2  940: }
                    941: 
1.10      bowersj2  942: sub end_message {
1.4       bowersj2  943:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    944: 
                    945:     if ($target ne 'helper') {
                    946:         return '';
                    947:     }
1.10      bowersj2  948:     Apache::lonhelper::message->new();
                    949:     return '';
1.5       bowersj2  950: }
                    951: 
                    952: sub render {
                    953:     my $self = shift;
                    954: 
                    955:     return $self->{MESSAGE_TEXT};
                    956: }
                    957: # If a NEXTSTATE was given, switch to it
                    958: sub postprocess {
                    959:     my $self = shift;
                    960:     if (defined($self->{NEXTSTATE})) {
                    961:         $helper->changeState($self->{NEXTSTATE});
                    962:     }
1.6       bowersj2  963: 
                    964:     return 1;
1.5       bowersj2  965: }
                    966: 1;
                    967: 
                    968: package Apache::lonhelper::choices;
                    969: 
                    970: =pod
                    971: 
                    972: =head2 Element: choices
                    973: 
                    974: Choice states provide a single choice to the user as a text selection box.
                    975: A "choice" is two pieces of text, one which will be displayed to the user
                    976: (the "human" value), and one which will be passed back to the program
                    977: (the "computer" value). For instance, a human may choose from a list of
                    978: resources on disk by title, while your program wants the file name.
                    979: 
                    980: <choices> takes an attribute "variable" to control which helper variable
                    981: the result is stored in.
                    982: 
                    983: <choices> takes an attribute "multichoice" which, if set to a true
                    984: value, will allow the user to select multiple choices.
                    985: 
1.26      bowersj2  986: <choices> takes an attribute "allowempty" which, if set to a true 
                    987: value, will allow the user to select none of the choices without raising
                    988: an error message.
                    989: 
1.5       bowersj2  990: B<SUB-TAGS>
                    991: 
                    992: <choices> can have the following subtags:
                    993: 
                    994: =over 4
                    995: 
                    996: =item * <nextstate>state_name</nextstate>: If given, this will cause the
                    997:       choice element to transition to the given state after executing. If
                    998:       this is used, do not pass nextstates to the <choice> tag.
                    999: 
                   1000: =item * <choice />: If the choices are static,
                   1001:       this element will allow you to specify them. Each choice
                   1002:       contains  attribute, "computer", as described above. The
                   1003:       content of the tag will be used as the human label.
                   1004:       For example,  
                   1005:       <choice computer='234-12-7312'>Bobby McDormik</choice>.
                   1006: 
1.13      bowersj2 1007:       <choice> can take a parameter "eval", which if set to
                   1008:       a true value, will cause the contents of the tag to be
                   1009:       evaluated as it would be in an <eval> tag; see <eval> tag
                   1010:       below.
                   1011: 
1.5       bowersj2 1012: <choice> may optionally contain a 'nextstate' attribute, which
                   1013: will be the state transisitoned to if the choice is made, if
                   1014: the choice is not multichoice.
                   1015: 
                   1016: =back
                   1017: 
                   1018: To create the choices programmatically, either wrap the choices in 
                   1019: <condition> tags (prefered), or use an <exec> block inside the <choice>
                   1020: tag. Store the choices in $state->{CHOICES}, which is a list of list
                   1021: references, where each list has three strings. The first is the human
                   1022: name, the second is the computer name. and the third is the option
                   1023: next state. For example:
                   1024: 
                   1025:  <exec>
                   1026:     for (my $i = 65; $i < 65 + 26; $i++) {
                   1027:         push @{$state->{CHOICES}}, [chr($i), $i, 'next'];
                   1028:     }
                   1029:  </exec>
                   1030: 
                   1031: This will allow the user to select from the letters A-Z (in ASCII), while
                   1032: passing the ASCII value back into the helper variables, and the state
                   1033: will in all cases transition to 'next'.
                   1034: 
                   1035: You can mix and match methods of creating choices, as long as you always 
                   1036: "push" onto the choice list, rather then wiping it out. (You can even 
                   1037: remove choices programmatically, but that would probably be bad form.)
                   1038: 
1.25      bowersj2 1039: B<defaultvalue support>
                   1040: 
                   1041: Choices supports default values both in multichoice and single choice mode.
                   1042: In single choice mode, have the defaultvalue tag's function return the 
                   1043: computer value of the box you want checked. If the function returns a value
                   1044: that does not correspond to any of the choices, the default behavior of selecting
                   1045: the first choice will be preserved.
                   1046: 
                   1047: For multichoice, return a string with the computer values you want checked,
                   1048: delimited by triple pipes. Note this matches how the result of the <choices>
                   1049: tag is stored in the {VARS} hash.
                   1050: 
1.5       bowersj2 1051: =cut
                   1052: 
                   1053: no strict;
                   1054: @ISA = ("Apache::lonhelper::element");
                   1055: use strict;
                   1056: 
                   1057: BEGIN {
1.7       bowersj2 1058:     &Apache::lonhelper::register('Apache::lonhelper::choices',
1.5       bowersj2 1059:                               ('choice', 'choices'));
                   1060: }
                   1061: 
                   1062: sub new {
                   1063:     my $ref = Apache::lonhelper::element->new();
                   1064:     bless($ref);
                   1065: }
                   1066: 
                   1067: # CONSTRUCTION: Construct the message element from the XML
                   1068: sub start_choices {
                   1069:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1070: 
                   1071:     if ($target ne 'helper') {
                   1072:         return '';
                   1073:     }
                   1074: 
                   1075:     # Need to initialize the choices list, so everything can assume it exists
1.24      sakharuk 1076:     $paramHash->{'variable'} = $token->[2]{'variable'} if (!defined($paramHash->{'variable'}));
1.5       bowersj2 1077:     $helper->declareVar($paramHash->{'variable'});
                   1078:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.26      bowersj2 1079:     $paramHash->{'allowempty'} = $token->[2]{'allowempty'};
1.5       bowersj2 1080:     $paramHash->{CHOICES} = [];
                   1081:     return '';
                   1082: }
                   1083: 
                   1084: sub end_choices {
                   1085:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1086: 
                   1087:     if ($target ne 'helper') {
                   1088:         return '';
                   1089:     }
                   1090:     Apache::lonhelper::choices->new();
                   1091:     return '';
                   1092: }
                   1093: 
                   1094: sub start_choice {
                   1095:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1096: 
                   1097:     if ($target ne 'helper') {
                   1098:         return '';
                   1099:     }
                   1100: 
                   1101:     my $computer = $token->[2]{'computer'};
                   1102:     my $human = &Apache::lonxml::get_all_text('/choice',
                   1103:                                               $parser);
                   1104:     my $nextstate = $token->[2]{'nextstate'};
1.13      bowersj2 1105:     my $evalFlag = $token->[2]{'eval'};
                   1106:     push @{$paramHash->{CHOICES}}, [$human, $computer, $nextstate, 
                   1107:                                     $evalFlag];
1.5       bowersj2 1108:     return '';
                   1109: }
                   1110: 
                   1111: sub end_choice {
                   1112:     return '';
                   1113: }
                   1114: 
                   1115: sub render {
                   1116:     # START HERE: Replace this with correct choices code.
                   1117:     my $self = shift;
                   1118:     my $var = $self->{'variable'};
                   1119:     my $buttons = '';
                   1120:     my $result = '';
                   1121: 
                   1122:     if ($self->{'multichoice'}) {
1.6       bowersj2 1123:         $result .= <<SCRIPT;
1.5       bowersj2 1124: <script>
1.18      bowersj2 1125:     function checkall(value, checkName) {
1.15      bowersj2 1126: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
1.18      bowersj2 1127:             ele = document.forms.helpform.elements[i];
                   1128:             if (ele.name == checkName + '.forminput') {
                   1129:                 document.forms.helpform.elements[i].checked=value;
                   1130:             }
1.5       bowersj2 1131:         }
                   1132:     }
                   1133: </script>
                   1134: SCRIPT
1.25      bowersj2 1135:     }
                   1136: 
                   1137:     # Only print "select all" and "unselect all" if there are five or
                   1138:     # more choices; fewer then that and it looks silly.
                   1139:     if ($self->{'multichoice'} && scalar(@{$self->{CHOICES}}) > 4) {
1.5       bowersj2 1140:         $buttons = <<BUTTONS;
                   1141: <br />
1.18      bowersj2 1142: <input type="button" onclick="checkall(true, '$var')" value="Select All" />
                   1143: <input type="button" onclick="checkall(false, '$var')" value="Unselect All" />
1.6       bowersj2 1144: <br />&nbsp;
1.5       bowersj2 1145: BUTTONS
                   1146:     }
                   1147: 
1.16      bowersj2 1148:     if (defined $self->{ERROR_MSG}) {
1.6       bowersj2 1149:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br />';
1.5       bowersj2 1150:     }
                   1151: 
                   1152:     $result .= $buttons;
1.6       bowersj2 1153:     
1.5       bowersj2 1154:     $result .= "<table>\n\n";
                   1155: 
1.25      bowersj2 1156:     my %checkedChoices;
                   1157:     my $checkedChoicesFunc;
                   1158: 
                   1159:     if (defined($self->{DEFAULT_VALUE})) {
                   1160:         $checkedChoicesFunc = eval ($self->{DEFAULT_VALUE});
                   1161:         die 'Error in default value code for variable ' . 
                   1162:             {'variable'} . ', Perl said:' . $@ if $@;
                   1163:     } else {
                   1164:         $checkedChoicesFunc = sub { return ''; };
                   1165:     }
                   1166: 
                   1167:     # Process which choices should be checked.
                   1168:     if ($self->{'multichoice'}) {
                   1169:         for my $selectedChoice (split(/\|\|\|/, (&$checkedChoicesFunc($helper, $self)))) {
                   1170:             $checkedChoices{$selectedChoice} = 1;
                   1171:         }
                   1172:     } else {
                   1173:         # single choice
                   1174:         my $selectedChoice = &$checkedChoicesFunc($helper, $self);
                   1175:         
                   1176:         my $foundChoice = 0;
                   1177:         
                   1178:         # check that the choice is in the list of choices.
                   1179:         for my $choice (@{$self->{CHOICES}}) {
                   1180:             if ($choice->[1] eq $selectedChoice) {
                   1181:                 $checkedChoices{$choice->[1]} = 1;
                   1182:                 $foundChoice = 1;
                   1183:             }
                   1184:         }
                   1185:         
                   1186:         # If we couldn't find the choice, pick the first one 
                   1187:         if (!$foundChoice) {
                   1188:             $checkedChoices{$self->{CHOICES}->[0]->[1]} = 1;
                   1189:         }
                   1190:     }
                   1191: 
1.5       bowersj2 1192:     my $type = "radio";
                   1193:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
                   1194:     foreach my $choice (@{$self->{CHOICES}}) {
                   1195:         $result .= "<tr>\n<td width='20'>&nbsp;</td>\n";
                   1196:         $result .= "<td valign='top'><input type='$type' name='$var.forminput'"
                   1197:             . "' value='" . 
                   1198:             HTML::Entities::encode($choice->[1]) 
                   1199:             . "'";
1.25      bowersj2 1200:         if ($checkedChoices{$choice->[1]}) {
1.5       bowersj2 1201:             $result .= " checked ";
                   1202:         }
1.13      bowersj2 1203:         my $choiceLabel = $choice->[0];
                   1204:         if ($choice->[4]) {  # if we need to evaluate this choice
                   1205:             $choiceLabel = "sub { my $helper = shift; my $state = shift;" .
                   1206:                 $choiceLabel . "}";
                   1207:             $choiceLabel = eval($choiceLabel);
                   1208:             $choiceLabel = &$choiceLabel($helper, $self);
                   1209:         }
                   1210:         $result .= "/></td><td> " . $choiceLabel . "</td></tr>\n";
1.5       bowersj2 1211:     }
                   1212:     $result .= "</table>\n\n\n";
                   1213:     $result .= $buttons;
                   1214: 
                   1215:     return $result;
                   1216: }
                   1217: 
                   1218: # If a NEXTSTATE was given or a nextstate for this choice was
                   1219: # given, switch to it
                   1220: sub postprocess {
                   1221:     my $self = shift;
                   1222:     my $chosenValue = $ENV{'form.' . $self->{'variable'} . '.forminput'};
                   1223: 
1.26      bowersj2 1224:     if (!defined($chosenValue) && !$self->{'allowempty'}) {
1.6       bowersj2 1225:         $self->{ERROR_MSG} = "You must choose one or more choices to" .
                   1226:             " continue.";
                   1227:         return 0;
                   1228:     }
                   1229: 
1.28      bowersj2 1230:     if (ref($chosenValue)) {
                   1231:         $helper->{VARS}->{$self->{'variable'}} = join('|||', @$chosenValue);
1.6       bowersj2 1232:     }
                   1233: 
1.5       bowersj2 1234:     if (defined($self->{NEXTSTATE})) {
                   1235:         $helper->changeState($self->{NEXTSTATE});
                   1236:     }
                   1237:     
                   1238:     foreach my $choice (@{$self->{CHOICES}}) {
                   1239:         if ($choice->[1] eq $chosenValue) {
                   1240:             if (defined($choice->[2])) {
                   1241:                 $helper->changeState($choice->[2]);
                   1242:             }
                   1243:         }
                   1244:     }
1.6       bowersj2 1245:     return 1;
1.5       bowersj2 1246: }
                   1247: 1;
                   1248: 
                   1249: package Apache::lonhelper::date;
                   1250: 
                   1251: =pod
                   1252: 
                   1253: =head2 Element: date
                   1254: 
                   1255: Date elements allow the selection of a date with a drop down list.
                   1256: 
                   1257: Date elements can take two attributes:
                   1258: 
                   1259: =over 4
                   1260: 
                   1261: =item * B<variable>: The name of the variable to store the chosen
                   1262:         date in. Required.
                   1263: 
                   1264: =item * B<hoursminutes>: If a true value, the date will show hours
                   1265:         and minutes, as well as month/day/year. If false or missing,
                   1266:         the date will only show the month, day, and year.
                   1267: 
                   1268: =back
                   1269: 
                   1270: Date elements contain only an option <nextstate> tag to determine
                   1271: the next state.
                   1272: 
                   1273: Example:
                   1274: 
                   1275:  <date variable="DUE_DATE" hoursminutes="1">
                   1276:    <nextstate>choose_why</nextstate>
                   1277:    </date>
                   1278: 
                   1279: =cut
                   1280: 
                   1281: no strict;
                   1282: @ISA = ("Apache::lonhelper::element");
                   1283: use strict;
                   1284: 
                   1285: use Time::localtime;
                   1286: 
                   1287: BEGIN {
1.7       bowersj2 1288:     &Apache::lonhelper::register('Apache::lonhelper::date',
1.5       bowersj2 1289:                               ('date'));
                   1290: }
                   1291: 
                   1292: # Don't need to override the "new" from element
                   1293: sub new {
                   1294:     my $ref = Apache::lonhelper::element->new();
                   1295:     bless($ref);
                   1296: }
                   1297: 
                   1298: my @months = ("January", "February", "March", "April", "May", "June", "July",
                   1299: 	      "August", "September", "October", "November", "December");
                   1300: 
                   1301: # CONSTRUCTION: Construct the message element from the XML
                   1302: sub start_date {
                   1303:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1304: 
                   1305:     if ($target ne 'helper') {
                   1306:         return '';
                   1307:     }
                   1308: 
                   1309:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1310:     $helper->declareVar($paramHash->{'variable'});
                   1311:     $paramHash->{'hoursminutes'} = $token->[2]{'hoursminutes'};
                   1312: }
                   1313: 
                   1314: sub end_date {
                   1315:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1316: 
                   1317:     if ($target ne 'helper') {
                   1318:         return '';
                   1319:     }
                   1320:     Apache::lonhelper::date->new();
                   1321:     return '';
                   1322: }
                   1323: 
                   1324: sub render {
                   1325:     my $self = shift;
                   1326:     my $result = "";
                   1327:     my $var = $self->{'variable'};
                   1328: 
                   1329:     my $date;
                   1330:     
                   1331:     # Default date: The current hour.
                   1332:     $date = localtime();
                   1333:     $date->min(0);
                   1334: 
                   1335:     if (defined $self->{ERROR_MSG}) {
                   1336:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   1337:     }
                   1338: 
                   1339:     # Month
                   1340:     my $i;
                   1341:     $result .= "<select name='${var}month'>\n";
                   1342:     for ($i = 0; $i < 12; $i++) {
                   1343:         if ($i == $date->mon) {
                   1344:             $result .= "<option value='$i' selected>";
                   1345:         } else {
                   1346:             $result .= "<option value='$i'>";
                   1347:         }
                   1348:         $result .= $months[$i] . "</option>\n";
                   1349:     }
                   1350:     $result .= "</select>\n";
                   1351: 
                   1352:     # Day
                   1353:     $result .= "<select name='${var}day'>\n";
                   1354:     for ($i = 1; $i < 32; $i++) {
                   1355:         if ($i == $date->mday) {
                   1356:             $result .= '<option selected>';
                   1357:         } else {
                   1358:             $result .= '<option>';
                   1359:         }
                   1360:         $result .= "$i</option>\n";
                   1361:     }
                   1362:     $result .= "</select>,\n";
                   1363: 
                   1364:     # Year
                   1365:     $result .= "<select name='${var}year'>\n";
                   1366:     for ($i = 2000; $i < 2030; $i++) { # update this after 64-bit dates
                   1367:         if ($date->year + 1900 == $i) {
                   1368:             $result .= "<option selected>";
                   1369:         } else {
                   1370:             $result .= "<option>";
                   1371:         }
                   1372:         $result .= "$i</option>\n";
                   1373:     }
                   1374:     $result .= "</select>,\n";
                   1375: 
                   1376:     # Display Hours and Minutes if they are called for
                   1377:     if ($self->{'hoursminutes'}) {
                   1378:         # Build hour
                   1379:         $result .= "<select name='${var}hour'>\n";
                   1380:         $result .= "<option " . ($date->hour == 0 ? 'selected ':'') .
                   1381:             " value='0'>midnight</option>\n";
                   1382:         for ($i = 1; $i < 12; $i++) {
                   1383:             if ($date->hour == $i) {
                   1384:                 $result .= "<option selected value='$i'>$i a.m.</option>\n";
                   1385:             } else {
                   1386:                 $result .= "<option value='$i'>$i a.m</option>\n";
                   1387:             }
                   1388:         }
                   1389:         $result .= "<option " . ($date->hour == 12 ? 'selected ':'') .
                   1390:             " value='12'>noon</option>\n";
                   1391:         for ($i = 13; $i < 24; $i++) {
                   1392:             my $printedHour = $i - 12;
                   1393:             if ($date->hour == $i) {
                   1394:                 $result .= "<option selected value='$i'>$printedHour p.m.</option>\n";
                   1395:             } else {
                   1396:                 $result .= "<option value='$i'>$printedHour p.m.</option>\n";
                   1397:             }
                   1398:         }
                   1399: 
                   1400:         $result .= "</select> :\n";
                   1401: 
                   1402:         $result .= "<select name='${var}minute'>\n";
                   1403:         for ($i = 0; $i < 60; $i++) {
                   1404:             my $printedMinute = $i;
                   1405:             if ($i < 10) {
                   1406:                 $printedMinute = "0" . $printedMinute;
                   1407:             }
                   1408:             if ($date->min == $i) {
                   1409:                 $result .= "<option selected>";
                   1410:             } else {
                   1411:                 $result .= "<option>";
                   1412:             }
                   1413:             $result .= "$printedMinute</option>\n";
                   1414:         }
                   1415:         $result .= "</select>\n";
                   1416:     }
                   1417: 
                   1418:     return $result;
                   1419: 
                   1420: }
                   1421: # If a NEXTSTATE was given, switch to it
                   1422: sub postprocess {
                   1423:     my $self = shift;
                   1424:     my $var = $self->{'variable'};
                   1425:     my $month = $ENV{'form.' . $var . 'month'}; 
                   1426:     my $day = $ENV{'form.' . $var . 'day'}; 
                   1427:     my $year = $ENV{'form.' . $var . 'year'}; 
                   1428:     my $min = 0; 
                   1429:     my $hour = 0;
                   1430:     if ($self->{'hoursminutes'}) {
                   1431:         $min = $ENV{'form.' . $var . 'minute'};
                   1432:         $hour = $ENV{'form.' . $var . 'hour'};
                   1433:     }
                   1434: 
                   1435:     my $chosenDate = Time::Local::timelocal(0, $min, $hour, $day, $month, $year);
                   1436:     # Check to make sure that the date was not automatically co-erced into a 
                   1437:     # valid date, as we want to flag that as an error
                   1438:     # This happens for "Feb. 31", for instance, which is coerced to March 2 or
                   1439:     # 3, depending on if it's a leapyear
                   1440:     my $checkDate = localtime($chosenDate);
                   1441: 
                   1442:     if ($checkDate->mon != $month || $checkDate->mday != $day ||
                   1443:         $checkDate->year + 1900 != $year) {
                   1444:         $self->{ERROR_MSG} = "Can't use " . $months[$month] . " $day, $year as a "
                   1445:             . "date because it doesn't exist. Please enter a valid date.";
1.6       bowersj2 1446:         return 0;
1.5       bowersj2 1447:     }
                   1448: 
                   1449:     $helper->{VARS}->{$var} = $chosenDate;
                   1450: 
                   1451:     if (defined($self->{NEXTSTATE})) {
                   1452:         $helper->changeState($self->{NEXTSTATE});
                   1453:     }
1.6       bowersj2 1454: 
                   1455:     return 1;
1.5       bowersj2 1456: }
                   1457: 1;
                   1458: 
                   1459: package Apache::lonhelper::resource;
                   1460: 
                   1461: =pod
                   1462: 
                   1463: =head2 Element: resource
                   1464: 
                   1465: <resource> elements allow the user to select one or multiple resources
                   1466: from the current course. You can filter out which resources they can view,
                   1467: and filter out which resources they can select. The course will always
                   1468: be displayed fully expanded, because of the difficulty of maintaining
                   1469: selections across folder openings and closings. If this is fixed, then
                   1470: the user can manipulate the folders.
                   1471: 
                   1472: <resource> takes the standard variable attribute to control what helper
                   1473: variable stores the results. It also takes a "multichoice" attribute,
1.17      bowersj2 1474: which controls whether the user can select more then one resource. The 
                   1475: "toponly" attribute controls whether the resource display shows just the
                   1476: resources in that sequence, or recurses into all sub-sequences, defaulting
1.29      bowersj2 1477: to false. The "suppressEmptySequences" attribute reflects the 
                   1478: suppressEmptySequences argument to the render routine, which will cause
                   1479: folders that have all of their contained resources filtered out to also
                   1480: be filtered out.
1.5       bowersj2 1481: 
                   1482: B<SUB-TAGS>
                   1483: 
                   1484: =over 4
                   1485: 
                   1486: =item * <filterfunc>: If you want to filter what resources are displayed
                   1487:   to the user, use a filter func. The <filterfunc> tag should contain
                   1488:   Perl code that when wrapped with "sub { my $res = shift; " and "}" is 
                   1489:   a function that returns true if the resource should be displayed, 
                   1490:   and false if it should be skipped. $res is a resource object. 
                   1491:   (See Apache::lonnavmaps documentation for information about the 
                   1492:   resource object.)
                   1493: 
                   1494: =item * <choicefunc>: Same as <filterfunc>, except that controls whether
                   1495:   the given resource can be chosen. (It is almost always a good idea to
                   1496:   show the user the folders, for instance, but you do not always want to 
                   1497:   let the user select them.)
                   1498: 
                   1499: =item * <nextstate>: Standard nextstate behavior.
                   1500: 
                   1501: =item * <valuefunc>: This function controls what is returned by the resource
                   1502:   when the user selects it. Like filterfunc and choicefunc, it should be
                   1503:   a function fragment that when wrapped by "sub { my $res = shift; " and
                   1504:   "}" returns a string representing what you want to have as the value. By
                   1505:   default, the value will be the resource ID of the object ($res->{ID}).
                   1506: 
1.13      bowersj2 1507: =item * <mapurl>: If the URL of a map is given here, only that map
                   1508:   will be displayed, instead of the whole course.
                   1509: 
1.5       bowersj2 1510: =back
                   1511: 
                   1512: =cut
                   1513: 
                   1514: no strict;
                   1515: @ISA = ("Apache::lonhelper::element");
                   1516: use strict;
                   1517: 
                   1518: BEGIN {
1.7       bowersj2 1519:     &Apache::lonhelper::register('Apache::lonhelper::resource',
1.5       bowersj2 1520:                               ('resource', 'filterfunc', 
1.13      bowersj2 1521:                                'choicefunc', 'valuefunc',
                   1522:                                'mapurl'));
1.5       bowersj2 1523: }
                   1524: 
                   1525: sub new {
                   1526:     my $ref = Apache::lonhelper::element->new();
                   1527:     bless($ref);
                   1528: }
                   1529: 
                   1530: # CONSTRUCTION: Construct the message element from the XML
                   1531: sub start_resource {
                   1532:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1533: 
                   1534:     if ($target ne 'helper') {
                   1535:         return '';
                   1536:     }
                   1537: 
                   1538:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1539:     $helper->declareVar($paramHash->{'variable'});
1.14      bowersj2 1540:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.29      bowersj2 1541:     $paramHash->{'suppressEmptySequences'} = $token->[2]{'suppressEmptySequences'};
1.17      bowersj2 1542:     $paramHash->{'toponly'} = $token->[2]{'toponly'};
1.5       bowersj2 1543:     return '';
                   1544: }
                   1545: 
                   1546: sub end_resource {
                   1547:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1548: 
                   1549:     if ($target ne 'helper') {
                   1550:         return '';
                   1551:     }
                   1552:     if (!defined($paramHash->{FILTER_FUNC})) {
                   1553:         $paramHash->{FILTER_FUNC} = sub {return 1;};
                   1554:     }
                   1555:     if (!defined($paramHash->{CHOICE_FUNC})) {
                   1556:         $paramHash->{CHOICE_FUNC} = sub {return 1;};
                   1557:     }
                   1558:     if (!defined($paramHash->{VALUE_FUNC})) {
                   1559:         $paramHash->{VALUE_FUNC} = sub {my $res = shift; return $res->{ID}; };
                   1560:     }
                   1561:     Apache::lonhelper::resource->new();
1.4       bowersj2 1562:     return '';
                   1563: }
                   1564: 
1.5       bowersj2 1565: sub start_filterfunc {
                   1566:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1567: 
                   1568:     if ($target ne 'helper') {
                   1569:         return '';
                   1570:     }
                   1571: 
                   1572:     my $contents = Apache::lonxml::get_all_text('/filterfunc',
                   1573:                                                 $parser);
                   1574:     $contents = 'sub { my $res = shift; ' . $contents . '}';
                   1575:     $paramHash->{FILTER_FUNC} = eval $contents;
                   1576: }
                   1577: 
                   1578: sub end_filterfunc { return ''; }
                   1579: 
                   1580: sub start_choicefunc {
                   1581:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1582: 
                   1583:     if ($target ne 'helper') {
                   1584:         return '';
                   1585:     }
                   1586: 
                   1587:     my $contents = Apache::lonxml::get_all_text('/choicefunc',
                   1588:                                                 $parser);
                   1589:     $contents = 'sub { my $res = shift; ' . $contents . '}';
                   1590:     $paramHash->{CHOICE_FUNC} = eval $contents;
                   1591: }
                   1592: 
                   1593: sub end_choicefunc { return ''; }
                   1594: 
                   1595: sub start_valuefunc {
                   1596:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1597: 
                   1598:     if ($target ne 'helper') {
                   1599:         return '';
                   1600:     }
                   1601: 
                   1602:     my $contents = Apache::lonxml::get_all_text('/valuefunc',
                   1603:                                                 $parser);
                   1604:     $contents = 'sub { my $res = shift; ' . $contents . '}';
                   1605:     $paramHash->{VALUE_FUNC} = eval $contents;
                   1606: }
                   1607: 
                   1608: sub end_valuefunc { return ''; }
                   1609: 
1.13      bowersj2 1610: sub start_mapurl {
                   1611:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1612: 
                   1613:     if ($target ne 'helper') {
                   1614:         return '';
                   1615:     }
                   1616: 
                   1617:     my $contents = Apache::lonxml::get_all_text('/mapurl',
                   1618:                                                 $parser);
1.14      bowersj2 1619:     $paramHash->{MAP_URL} = $contents;
1.13      bowersj2 1620: }
                   1621: 
                   1622: sub end_mapurl { return ''; }
                   1623: 
1.5       bowersj2 1624: # A note, in case I don't get to this before I leave.
                   1625: # If someone complains about the "Back" button returning them
                   1626: # to the previous folder state, instead of returning them to
                   1627: # the previous helper state, the *correct* answer is for the helper
                   1628: # to keep track of how many times the user has manipulated the folders,
                   1629: # and feed that to the history.go() call in the helper rendering routines.
                   1630: # If done correctly, the helper itself can keep track of how many times
                   1631: # it renders the same states, so it doesn't go in just this state, and
                   1632: # you can lean on the browser back button to make sure it all chains
                   1633: # correctly.
                   1634: # Right now, though, I'm just forcing all folders open.
                   1635: 
                   1636: sub render {
                   1637:     my $self = shift;
                   1638:     my $result = "";
                   1639:     my $var = $self->{'variable'};
                   1640:     my $curVal = $helper->{VARS}->{$var};
                   1641: 
1.15      bowersj2 1642:     my $buttons = '';
                   1643: 
                   1644:     if ($self->{'multichoice'}) {
                   1645:         $result = <<SCRIPT;
                   1646: <script>
1.18      bowersj2 1647:     function checkall(value, checkName) {
1.15      bowersj2 1648: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
                   1649:             ele = document.forms.helpform.elements[i];
1.18      bowersj2 1650:             if (ele.name == checkName + '.forminput') {
1.15      bowersj2 1651:                 document.forms.helpform.elements[i].checked=value;
                   1652:             }
                   1653:         }
                   1654:     }
                   1655: </script>
                   1656: SCRIPT
                   1657:         $buttons = <<BUTTONS;
                   1658: <br /> &nbsp;
1.18      bowersj2 1659: <input type="button" onclick="checkall(true, '$var')" value="Select All Resources" />
                   1660: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Resources" />
1.15      bowersj2 1661: <br /> &nbsp;
                   1662: BUTTONS
                   1663:     }
                   1664: 
1.5       bowersj2 1665:     if (defined $self->{ERROR_MSG}) {
1.14      bowersj2 1666:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
1.5       bowersj2 1667:     }
                   1668: 
1.15      bowersj2 1669:     $result .= $buttons;
                   1670: 
1.5       bowersj2 1671:     my $filterFunc = $self->{FILTER_FUNC};
                   1672:     my $choiceFunc = $self->{CHOICE_FUNC};
                   1673:     my $valueFunc = $self->{VALUE_FUNC};
1.13      bowersj2 1674:     my $mapUrl = $self->{MAP_URL};
1.14      bowersj2 1675:     my $multichoice = $self->{'multichoice'};
1.5       bowersj2 1676: 
                   1677:     # Create the composite function that renders the column on the nav map
                   1678:     # have to admit any language that lets me do this can't be all bad
                   1679:     #  - Jeremy (Pythonista) ;-)
                   1680:     my $checked = 0;
                   1681:     my $renderColFunc = sub {
                   1682:         my ($resource, $part, $params) = @_;
1.14      bowersj2 1683: 
                   1684:         my $inputType;
                   1685:         if ($multichoice) { $inputType = 'checkbox'; }
                   1686:         else {$inputType = 'radio'; }
                   1687: 
1.5       bowersj2 1688:         if (!&$choiceFunc($resource)) {
                   1689:             return '<td>&nbsp;</td>';
                   1690:         } else {
1.14      bowersj2 1691:             my $col = "<td><input type='$inputType' name='${var}.forminput' ";
                   1692:             if (!$checked && !$multichoice) {
1.5       bowersj2 1693:                 $col .= "checked ";
                   1694:                 $checked = 1;
                   1695:             }
                   1696:             $col .= "value='" . 
                   1697:                 HTML::Entities::encode(&$valueFunc($resource)) 
                   1698:                 . "' /></td>";
                   1699:             return $col;
                   1700:         }
                   1701:     };
                   1702: 
1.17      bowersj2 1703:     $ENV{'form.condition'} = !$self->{'toponly'};
1.5       bowersj2 1704:     $result .= 
                   1705:         &Apache::lonnavmaps::render( { 'cols' => [$renderColFunc, 
                   1706:                                                   Apache::lonnavmaps::resource()],
                   1707:                                        'showParts' => 0,
                   1708:                                        'filterFunc' => $filterFunc,
1.13      bowersj2 1709:                                        'resource_no_folder_link' => 1,
1.29      bowersj2 1710:                                        'suppressEmptySequences' => $self->{'suppressEmptySequences'},
1.13      bowersj2 1711:                                        'iterator_map' => $mapUrl }
1.5       bowersj2 1712:                                        );
1.15      bowersj2 1713: 
                   1714:     $result .= $buttons;
1.5       bowersj2 1715:                                                 
                   1716:     return $result;
                   1717: }
                   1718:     
                   1719: sub postprocess {
                   1720:     my $self = shift;
1.14      bowersj2 1721: 
                   1722:     if ($self->{'multichoice'} && !$helper->{VARS}->{$self->{'variable'}}) {
                   1723:         $self->{ERROR_MSG} = 'You must choose at least one resource to continue.';
                   1724:         return 0;
                   1725:     }
                   1726: 
1.5       bowersj2 1727:     if (defined($self->{NEXTSTATE})) {
                   1728:         $helper->changeState($self->{NEXTSTATE});
                   1729:     }
1.6       bowersj2 1730: 
                   1731:     return 1;
1.5       bowersj2 1732: }
                   1733: 
                   1734: 1;
                   1735: 
                   1736: package Apache::lonhelper::student;
                   1737: 
                   1738: =pod
                   1739: 
                   1740: =head2 Element: student
                   1741: 
                   1742: Student elements display a choice of students enrolled in the current
                   1743: course. Currently it is primitive; this is expected to evolve later.
                   1744: 
                   1745: Student elements take two attributes: "variable", which means what
                   1746: it usually does, and "multichoice", which if true allows the user
                   1747: to select multiple students.
                   1748: 
                   1749: =cut
                   1750: 
                   1751: no strict;
                   1752: @ISA = ("Apache::lonhelper::element");
                   1753: use strict;
                   1754: 
                   1755: 
                   1756: 
                   1757: BEGIN {
1.7       bowersj2 1758:     &Apache::lonhelper::register('Apache::lonhelper::student',
1.5       bowersj2 1759:                               ('student'));
                   1760: }
                   1761: 
                   1762: sub new {
                   1763:     my $ref = Apache::lonhelper::element->new();
                   1764:     bless($ref);
                   1765: }
1.4       bowersj2 1766: 
1.5       bowersj2 1767: sub start_student {
1.4       bowersj2 1768:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1769: 
                   1770:     if ($target ne 'helper') {
                   1771:         return '';
                   1772:     }
                   1773: 
1.5       bowersj2 1774:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1775:     $helper->declareVar($paramHash->{'variable'});
                   1776:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.12      bowersj2 1777:     if (defined($token->[2]{'nextstate'})) {
                   1778:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
                   1779:     }
                   1780:     
1.5       bowersj2 1781: }    
                   1782: 
                   1783: sub end_student {
                   1784:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1785: 
                   1786:     if ($target ne 'helper') {
                   1787:         return '';
                   1788:     }
                   1789:     Apache::lonhelper::student->new();
1.3       bowersj2 1790: }
1.5       bowersj2 1791: 
                   1792: sub render {
                   1793:     my $self = shift;
                   1794:     my $result = '';
                   1795:     my $buttons = '';
1.18      bowersj2 1796:     my $var = $self->{'variable'};
1.5       bowersj2 1797: 
                   1798:     if ($self->{'multichoice'}) {
                   1799:         $result = <<SCRIPT;
                   1800: <script>
1.18      bowersj2 1801:     function checkall(value, checkName) {
1.15      bowersj2 1802: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
1.18      bowersj2 1803:             ele = document.forms.helpform.elements[i];
                   1804:             if (ele.name == checkName + '.forminput') {
                   1805:                 document.forms.helpform.elements[i].checked=value;
                   1806:             }
1.5       bowersj2 1807:         }
                   1808:     }
                   1809: </script>
                   1810: SCRIPT
                   1811:         $buttons = <<BUTTONS;
                   1812: <br />
1.18      bowersj2 1813: <input type="button" onclick="checkall(true, '$var')" value="Select All Students" />
                   1814: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Students" />
1.5       bowersj2 1815: <br />
                   1816: BUTTONS
                   1817:     }
                   1818: 
                   1819:     if (defined $self->{ERROR_MSG}) {
                   1820:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   1821:     }
                   1822: 
                   1823:     # Load up the students
                   1824:     my $choices = &Apache::loncoursedata::get_classlist();
                   1825:     my @keys = keys %{$choices};
                   1826: 
                   1827:     # Constants
                   1828:     my $section = Apache::loncoursedata::CL_SECTION();
                   1829:     my $fullname = Apache::loncoursedata::CL_FULLNAME();
                   1830: 
                   1831:     # Sort by: Section, name
                   1832:     @keys = sort {
                   1833:         if ($choices->{$a}->[$section] ne $choices->{$b}->[$section]) {
                   1834:             return $choices->{$a}->[$section] cmp $choices->{$b}->[$section];
                   1835:         }
                   1836:         return $choices->{$a}->[$fullname] cmp $choices->{$b}->[$fullname];
                   1837:     } @keys;
                   1838: 
                   1839:     my $type = 'radio';
                   1840:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
                   1841:     $result .= "<table cellspacing='2' cellpadding='2' border='0'>\n";
                   1842:     $result .= "<tr><td></td><td align='center'><b>Student Name</b></td>".
                   1843:         "<td align='center'><b>Section</b></td></tr>";
                   1844: 
                   1845:     my $checked = 0;
                   1846:     foreach (@keys) {
                   1847:         $result .= "<tr><td><input type='$type' name='" .
                   1848:             $self->{'variable'} . '.forminput' . "'";
                   1849:             
                   1850:         if (!$self->{'multichoice'} && !$checked) {
                   1851:             $result .= " checked ";
                   1852:             $checked = 1;
                   1853:         }
                   1854:         $result .=
1.19      bowersj2 1855:             " value='" . HTML::Entities::encode($_ . ':' . $choices->{$_}->[$section])
1.5       bowersj2 1856:             . "' /></td><td>"
                   1857:             . HTML::Entities::encode($choices->{$_}->[$fullname])
                   1858:             . "</td><td align='center'>" 
                   1859:             . HTML::Entities::encode($choices->{$_}->[$section])
                   1860:             . "</td></tr>\n";
                   1861:     }
                   1862: 
                   1863:     $result .= "</table>\n\n";
                   1864:     $result .= $buttons;    
1.4       bowersj2 1865:     
1.5       bowersj2 1866:     return $result;
                   1867: }
                   1868: 
1.6       bowersj2 1869: sub postprocess {
                   1870:     my $self = shift;
                   1871: 
                   1872:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
                   1873:     if (!$result) {
                   1874:         $self->{ERROR_MSG} = 'You must choose at least one student '.
                   1875:             'to continue.';
                   1876:         return 0;
                   1877:     }
                   1878: 
                   1879:     if (defined($self->{NEXTSTATE})) {
                   1880:         $helper->changeState($self->{NEXTSTATE});
                   1881:     }
                   1882: 
                   1883:     return 1;
                   1884: }
                   1885: 
1.5       bowersj2 1886: 1;
                   1887: 
                   1888: package Apache::lonhelper::files;
                   1889: 
                   1890: =pod
                   1891: 
                   1892: =head2 Element: files
                   1893: 
                   1894: files allows the users to choose files from a given directory on the
                   1895: server. It is always multichoice and stores the result as a triple-pipe
                   1896: delimited entry in the helper variables. 
                   1897: 
                   1898: Since it is extremely unlikely that you can actually code a constant
                   1899: representing the directory you wish to allow the user to search, <files>
                   1900: takes a subroutine that returns the name of the directory you wish to
                   1901: have the user browse.
                   1902: 
                   1903: files accepts the attribute "variable" to control where the files chosen
                   1904: are put. It accepts the attribute "multichoice" as the other attribute,
                   1905: defaulting to false, which if true will allow the user to select more
                   1906: then one choice. 
                   1907: 
                   1908: <files> accepts three subtags. One is the "nextstate" sub-tag that works
                   1909: as it does with the other tags. Another is a <filechoice> sub tag that
                   1910: is Perl code that, when surrounded by "sub {" and "}" will return a
                   1911: string representing what directory on the server to allow the user to 
                   1912: choose files from. Finally, the <filefilter> subtag should contain Perl
                   1913: code that when surrounded by "sub { my $filename = shift; " and "}",
                   1914: returns a true value if the user can pick that file, or false otherwise.
                   1915: The filename passed to the function will be just the name of the file, 
                   1916: with no path info.
                   1917: 
                   1918: =cut
                   1919: 
                   1920: no strict;
                   1921: @ISA = ("Apache::lonhelper::element");
                   1922: use strict;
                   1923: 
1.32    ! bowersj2 1924: use Apache::lonpubdir; # for getTitleString
        !          1925: 
1.5       bowersj2 1926: BEGIN {
1.7       bowersj2 1927:     &Apache::lonhelper::register('Apache::lonhelper::files',
                   1928:                                  ('files', 'filechoice', 'filefilter'));
1.5       bowersj2 1929: }
                   1930: 
                   1931: sub new {
                   1932:     my $ref = Apache::lonhelper::element->new();
                   1933:     bless($ref);
                   1934: }
                   1935: 
                   1936: sub start_files {
                   1937:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1938: 
                   1939:     if ($target ne 'helper') {
                   1940:         return '';
                   1941:     }
                   1942:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1943:     $helper->declareVar($paramHash->{'variable'});
                   1944:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
                   1945: }    
                   1946: 
                   1947: sub end_files {
                   1948:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1949: 
                   1950:     if ($target ne 'helper') {
                   1951:         return '';
                   1952:     }
                   1953:     if (!defined($paramHash->{FILTER_FUNC})) {
                   1954:         $paramHash->{FILTER_FUNC} = sub { return 1; };
                   1955:     }
                   1956:     Apache::lonhelper::files->new();
                   1957: }    
                   1958: 
                   1959: sub start_filechoice {
                   1960:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1961: 
                   1962:     if ($target ne 'helper') {
                   1963:         return '';
                   1964:     }
                   1965:     $paramHash->{'filechoice'} = Apache::lonxml::get_all_text('/filechoice',
                   1966:                                                               $parser);
                   1967: }
                   1968: 
                   1969: sub end_filechoice { return ''; }
                   1970: 
                   1971: sub start_filefilter {
                   1972:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1973: 
                   1974:     if ($target ne 'helper') {
                   1975:         return '';
                   1976:     }
                   1977: 
                   1978:     my $contents = Apache::lonxml::get_all_text('/filefilter',
                   1979:                                                 $parser);
                   1980:     $contents = 'sub { my $filename = shift; ' . $contents . '}';
                   1981:     $paramHash->{FILTER_FUNC} = eval $contents;
                   1982: }
                   1983: 
                   1984: sub end_filefilter { return ''; }
1.3       bowersj2 1985: 
                   1986: sub render {
                   1987:     my $self = shift;
1.5       bowersj2 1988:     my $result = '';
                   1989:     my $var = $self->{'variable'};
                   1990:     
                   1991:     my $subdirFunc = eval('sub {' . $self->{'filechoice'} . '}');
1.11      bowersj2 1992:     die 'Error in resource filter code for variable ' . 
                   1993:         {'variable'} . ', Perl said:' . $@ if $@;
                   1994: 
1.5       bowersj2 1995:     my $subdir = &$subdirFunc();
                   1996: 
                   1997:     my $filterFunc = $self->{FILTER_FUNC};
                   1998:     my $buttons = '';
1.22      bowersj2 1999:     my $type = 'radio';
                   2000:     if ($self->{'multichoice'}) {
                   2001:         $type = 'checkbox';
                   2002:     }
1.5       bowersj2 2003: 
                   2004:     if ($self->{'multichoice'}) {
                   2005:         $result = <<SCRIPT;
                   2006: <script>
1.18      bowersj2 2007:     function checkall(value, checkName) {
1.15      bowersj2 2008: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
                   2009:             ele = document.forms.helpform.elements[i];
1.18      bowersj2 2010:             if (ele.name == checkName + '.forminput') {
1.15      bowersj2 2011:                 document.forms.helpform.elements[i].checked=value;
1.5       bowersj2 2012:             }
                   2013:         }
                   2014:     }
1.21      bowersj2 2015: 
1.22      bowersj2 2016:     function checkallclass(value, className) {
1.21      bowersj2 2017:         for (i=0; i<document.forms.helpform.elements.length; i++) {
                   2018:             ele = document.forms.helpform.elements[i];
1.22      bowersj2 2019:             if (ele.type == "$type" && ele.onclick) {
1.21      bowersj2 2020:                 document.forms.helpform.elements[i].checked=value;
                   2021:             }
                   2022:         }
                   2023:     }
1.5       bowersj2 2024: </script>
                   2025: SCRIPT
1.15      bowersj2 2026:         $buttons = <<BUTTONS;
1.5       bowersj2 2027: <br /> &nbsp;
1.18      bowersj2 2028: <input type="button" onclick="checkall(true, '$var')" value="Select All Files" />
                   2029: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Files" />
1.23      bowersj2 2030: BUTTONS
                   2031: 
                   2032:         if ($helper->{VARS}->{'construction'}) {
                   2033:             $buttons .= <<BUTTONS;
1.22      bowersj2 2034: <input type="button" onclick="checkallclass(true, 'Published')" value="Select All Published" />
                   2035: <input type="button" onclick="checkallclass(false, 'Published')" value="Unselect All Published" />
1.5       bowersj2 2036: <br /> &nbsp;
                   2037: BUTTONS
1.23      bowersj2 2038:        }
1.5       bowersj2 2039:     }
                   2040: 
                   2041:     # Get the list of files in this directory.
                   2042:     my @fileList;
                   2043: 
                   2044:     # If the subdirectory is in local CSTR space
                   2045:     if ($subdir =~ m|/home/([^/]+)/public_html|) {
                   2046:         my $user = $1;
                   2047:         my $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
                   2048:         @fileList = &Apache::lonnet::dirlist($subdir, $domain, $user, '');
                   2049:     } else {
                   2050:         # local library server resource space
                   2051:         @fileList = &Apache::lonnet::dirlist($subdir, $ENV{'user.domain'}, $ENV{'user.name'}, '');
                   2052:     }
1.3       bowersj2 2053: 
1.5       bowersj2 2054:     $result .= $buttons;
                   2055: 
1.6       bowersj2 2056:     if (defined $self->{ERROR_MSG}) {
                   2057:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   2058:     }
                   2059: 
1.20      bowersj2 2060:     $result .= '<table border="0" cellpadding="2" cellspacing="0">';
1.5       bowersj2 2061: 
                   2062:     # Keeps track if there are no choices, prints appropriate error
                   2063:     # if there are none. 
                   2064:     my $choices = 0;
                   2065:     # Print each legitimate file choice.
                   2066:     for my $file (@fileList) {
                   2067:         $file = (split(/&/, $file))[0];
                   2068:         if ($file eq '.' || $file eq '..') {
                   2069:             next;
                   2070:         }
                   2071:         my $fileName = $subdir .'/'. $file;
                   2072:         if (&$filterFunc($file)) {
1.24      sakharuk 2073: 	    my $status;
                   2074: 	    my $color;
                   2075: 	    if ($helper->{VARS}->{'construction'}) {
                   2076: 		($status, $color) = @{fileState($subdir, $file)};
                   2077: 	    } else {
                   2078: 		$status = '';
                   2079: 		$color = '';
                   2080: 	    }
1.22      bowersj2 2081: 
1.32    ! bowersj2 2082:             # Get the title
        !          2083:             my $title = Apache::lonpubdir::getTitleString($fileName);
        !          2084: 
1.22      bowersj2 2085:             # Netscape 4 is stupid and there's nowhere to put the
                   2086:             # information on the input tag that the file is Published,
                   2087:             # Unpublished, etc. In *real* browsers we can just say
                   2088:             # "class='Published'" and check the className attribute of
                   2089:             # the input tag, but Netscape 4 is too stupid to understand
                   2090:             # that attribute, and un-comprehended attributes are not
                   2091:             # reflected into the object model. So instead, what I do 
                   2092:             # is either have or don't have an "onclick" handler that 
                   2093:             # does nothing, give Published files the onclick handler, and
                   2094:             # have the checker scripts check for that. Stupid and clumsy,
                   2095:             # and only gives us binary "yes/no" information (at least I
                   2096:             # couldn't figure out how to reach into the event handler's
                   2097:             # actual code to retreive a value), but it works well enough
                   2098:             # here.
1.23      bowersj2 2099:         
1.22      bowersj2 2100:             my $onclick = '';
1.23      bowersj2 2101:             if ($status eq 'Published' && $helper->{VARS}->{'construction'}) {
1.22      bowersj2 2102:                 $onclick = 'onclick="a=1" ';
                   2103:             }
1.20      bowersj2 2104:             $result .= '<tr><td align="right"' . " bgcolor='$color'>" .
1.22      bowersj2 2105:                 "<input $onclick type='$type' name='" . $var
1.5       bowersj2 2106:             . ".forminput' value='" . HTML::Entities::encode($fileName) .
                   2107:                 "'";
                   2108:             if (!$self->{'multichoice'} && $choices == 0) {
                   2109:                 $result .= ' checked';
                   2110:             }
1.32    ! bowersj2 2111:             $result .= "/></td><td bgcolor='$color'>" . $file . "</td>" .
        !          2112:                 "<td bgcolor='$color'>$title</td>" .
        !          2113:                 "<td bgcolor='$color'>$status</td>" . "</tr>\n";
1.5       bowersj2 2114:             $choices++;
                   2115:         }
                   2116:     }
                   2117: 
                   2118:     $result .= "</table>\n";
                   2119: 
                   2120:     if (!$choices) {
                   2121:         $result .= '<font color="#FF0000">There are no files available to select in this directory. Please go back and select another option.</font><br /><br />';
                   2122:     }
                   2123: 
                   2124:     $result .= $buttons;
                   2125: 
                   2126:     return $result;
1.20      bowersj2 2127: }
                   2128: 
                   2129: # Determine the state of the file: Published, unpublished, modified.
                   2130: # Return the color it should be in and a label as a two-element array
                   2131: # reference.
                   2132: # Logic lifted from lonpubdir.pm, even though I don't know that it's still
                   2133: # the most right thing to do.
                   2134: 
                   2135: sub fileState {
                   2136:     my $constructionSpaceDir = shift;
                   2137:     my $file = shift;
                   2138:     
                   2139:     my $docroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2140:     my $subdirpart = $constructionSpaceDir;
                   2141:     $subdirpart =~ s/^\/home\/$ENV{'user.name'}\/public_html//;
                   2142:     my $resdir = $docroot . '/res/' . $ENV{'user.domain'} . '/' . $ENV{'user.name'} .
                   2143:         $subdirpart;
                   2144: 
                   2145:     my @constructionSpaceFileStat = stat($constructionSpaceDir . '/' . $file);
                   2146:     my @resourceSpaceFileStat = stat($resdir . '/' . $file);
                   2147:     if (!@resourceSpaceFileStat) {
                   2148:         return ['Unpublished', '#FFCCCC'];
                   2149:     }
                   2150: 
                   2151:     my $constructionSpaceFileModified = $constructionSpaceFileStat[9];
                   2152:     my $resourceSpaceFileModified = $resourceSpaceFileStat[9];
                   2153:     
                   2154:     if ($constructionSpaceFileModified > $resourceSpaceFileModified) {
                   2155:         return ['Modified', '#FFFFCC'];
                   2156:     }
                   2157:     return ['Published', '#CCFFCC'];
1.4       bowersj2 2158: }
1.5       bowersj2 2159: 
1.4       bowersj2 2160: sub postprocess {
                   2161:     my $self = shift;
1.6       bowersj2 2162:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
                   2163:     if (!$result) {
                   2164:         $self->{ERROR_MSG} = 'You must choose at least one file '.
                   2165:             'to continue.';
                   2166:         return 0;
                   2167:     }
                   2168: 
1.5       bowersj2 2169:     if (defined($self->{NEXTSTATE})) {
                   2170:         $helper->changeState($self->{NEXTSTATE});
1.3       bowersj2 2171:     }
1.6       bowersj2 2172: 
                   2173:     return 1;
1.3       bowersj2 2174: }
1.8       bowersj2 2175: 
                   2176: 1;
                   2177: 
1.11      bowersj2 2178: package Apache::lonhelper::section;
                   2179: 
                   2180: =pod
                   2181: 
                   2182: =head2 Element: section
                   2183: 
                   2184: <section> allows the user to choose one or more sections from the current
                   2185: course.
                   2186: 
                   2187: It takes the standard attributes "variable", "multichoice", and
                   2188: "nextstate", meaning what they do for most other elements.
                   2189: 
                   2190: =cut
                   2191: 
                   2192: no strict;
                   2193: @ISA = ("Apache::lonhelper::choices");
                   2194: use strict;
                   2195: 
                   2196: BEGIN {
                   2197:     &Apache::lonhelper::register('Apache::lonhelper::section',
                   2198:                                  ('section'));
                   2199: }
                   2200: 
                   2201: sub new {
                   2202:     my $ref = Apache::lonhelper::choices->new();
                   2203:     bless($ref);
                   2204: }
                   2205: 
                   2206: sub start_section {
                   2207:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2208: 
                   2209:     if ($target ne 'helper') {
                   2210:         return '';
                   2211:     }
1.12      bowersj2 2212: 
                   2213:     $paramHash->{CHOICES} = [];
                   2214: 
1.11      bowersj2 2215:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   2216:     $helper->declareVar($paramHash->{'variable'});
                   2217:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
                   2218:     if (defined($token->[2]{'nextstate'})) {
1.12      bowersj2 2219:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
1.11      bowersj2 2220:     }
                   2221: 
                   2222:     # Populate the CHOICES element
                   2223:     my %choices;
                   2224: 
                   2225:     my $section = Apache::loncoursedata::CL_SECTION();
                   2226:     my $classlist = Apache::loncoursedata::get_classlist();
                   2227:     foreach (keys %$classlist) {
                   2228:         my $sectionName = $classlist->{$_}->[$section];
                   2229:         if (!$sectionName) {
                   2230:             $choices{"No section assigned"} = "";
                   2231:         } else {
                   2232:             $choices{$sectionName} = $sectionName;
                   2233:         }
1.12      bowersj2 2234:     } 
                   2235:    
1.11      bowersj2 2236:     for my $sectionName (sort(keys(%choices))) {
1.12      bowersj2 2237:         
1.11      bowersj2 2238:         push @{$paramHash->{CHOICES}}, [$sectionName, $sectionName];
                   2239:     }
                   2240: }    
                   2241: 
1.12      bowersj2 2242: sub end_section {
                   2243:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.11      bowersj2 2244: 
1.12      bowersj2 2245:     if ($target ne 'helper') {
                   2246:         return '';
                   2247:     }
                   2248:     Apache::lonhelper::section->new();
                   2249: }    
1.11      bowersj2 2250: 1;
                   2251: 
1.8       bowersj2 2252: package Apache::lonhelper::general;
                   2253: 
                   2254: =pod
                   2255: 
                   2256: =head2 General-purpose tag: <exec>
                   2257: 
                   2258: The contents of the exec tag are executed as Perl code, not inside a 
                   2259: safe space, so the full range of $ENV and such is available. The code
                   2260: will be executed as a subroutine wrapped with the following code:
                   2261: 
                   2262: "sub { my $helper = shift; my $state = shift;" and
                   2263: 
                   2264: "}"
                   2265: 
                   2266: The return value is ignored.
                   2267: 
                   2268: $helper is the helper object. Feel free to add methods to the helper
                   2269: object to support whatever manipulation you may need to do (for instance,
                   2270: overriding the form location if the state is the final state; see 
                   2271: lonparm.helper for an example).
                   2272: 
                   2273: $state is the $paramHash that has currently been generated and may
                   2274: be manipulated by the code in exec. Note that the $state is not yet
                   2275: an actual state B<object>, it is just a hash, so do not expect to
                   2276: be able to call methods on it.
                   2277: 
                   2278: =cut
                   2279: 
                   2280: BEGIN {
                   2281:     &Apache::lonhelper::register('Apache::lonhelper::general',
1.11      bowersj2 2282:                                  'exec', 'condition', 'clause',
                   2283:                                  'eval');
1.8       bowersj2 2284: }
                   2285: 
                   2286: sub start_exec {
                   2287:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2288: 
                   2289:     if ($target ne 'helper') {
                   2290:         return '';
                   2291:     }
                   2292:     
                   2293:     my $code = &Apache::lonxml::get_all_text('/exec', $parser);
                   2294:     
                   2295:     $code = eval ('sub { my $helper = shift; my $state = shift; ' .
                   2296:         $code . "}");
1.11      bowersj2 2297:     die 'Error in <exec>, Perl said: '. $@ if $@;
1.8       bowersj2 2298:     &$code($helper, $paramHash);
                   2299: }
                   2300: 
                   2301: sub end_exec { return ''; }
                   2302: 
                   2303: =pod
                   2304: 
                   2305: =head2 General-purpose tag: <condition>
                   2306: 
                   2307: The <condition> tag allows you to mask out parts of the helper code
                   2308: depending on some programatically determined condition. The condition
                   2309: tag contains a tag <clause> which contains perl code that when wrapped
                   2310: with "sub { my $helper = shift; my $state = shift; " and "}", returns
                   2311: a true value if the XML in the condition should be evaluated as a normal
                   2312: part of the helper, or false if it should be completely discarded.
                   2313: 
                   2314: The <clause> tag must be the first sub-tag of the <condition> tag or
                   2315: it will not work as expected.
                   2316: 
                   2317: =cut
                   2318: 
                   2319: # The condition tag just functions as a marker, it doesn't have
                   2320: # to "do" anything. Technically it doesn't even have to be registered
                   2321: # with the lonxml code, but I leave this here to be explicit about it.
                   2322: sub start_condition { return ''; }
                   2323: sub end_condition { return ''; }
                   2324: 
                   2325: sub start_clause {
                   2326:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2327: 
                   2328:     if ($target ne 'helper') {
                   2329:         return '';
                   2330:     }
                   2331:     
                   2332:     my $clause = Apache::lonxml::get_all_text('/clause', $parser);
                   2333:     $clause = eval('sub { my $helper = shift; my $state = shift; '
                   2334:         . $clause . '}');
1.11      bowersj2 2335:     die 'Error in clause of condition, Perl said: ' . $@ if $@;
1.8       bowersj2 2336:     if (!&$clause($helper, $paramHash)) {
                   2337:         # Discard all text until the /condition.
                   2338:         &Apache::lonxml::get_all_text('/condition', $parser);
                   2339:     }
                   2340: }
                   2341: 
                   2342: sub end_clause { return ''; }
1.11      bowersj2 2343: 
                   2344: =pod
                   2345: 
                   2346: =head2 General-purpose tag: <eval>
                   2347: 
                   2348: The <eval> tag will be evaluated as a subroutine call passed in the
                   2349: current helper object and state hash as described in <condition> above,
                   2350: but is expected to return a string to be printed directly to the
                   2351: screen. This is useful for dynamically generating messages. 
                   2352: 
                   2353: =cut
                   2354: 
                   2355: # This is basically a type of message.
                   2356: # Programmatically setting $paramHash->{NEXTSTATE} would work, though
                   2357: # it's probably bad form.
                   2358: 
                   2359: sub start_eval {
                   2360:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2361: 
                   2362:     if ($target ne 'helper') {
                   2363:         return '';
                   2364:     }
                   2365:     
                   2366:     my $program = Apache::lonxml::get_all_text('/eval', $parser);
                   2367:     $program = eval('sub { my $helper = shift; my $state = shift; '
                   2368:         . $program . '}');
                   2369:     die 'Error in eval code, Perl said: ' . $@ if $@;
                   2370:     $paramHash->{MESSAGE_TEXT} = &$program($helper, $paramHash);
                   2371: }
                   2372: 
                   2373: sub end_eval { 
                   2374:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2375: 
                   2376:     if ($target ne 'helper') {
                   2377:         return '';
                   2378:     }
                   2379: 
                   2380:     Apache::lonhelper::message->new();
                   2381: }
                   2382: 
1.13      bowersj2 2383: 1;
                   2384: 
1.27      bowersj2 2385: package Apache::lonhelper::final;
                   2386: 
                   2387: =pod
                   2388: 
                   2389: =head2 Element: final
                   2390: 
                   2391: <final> is a special element that works with helpers that use the <finalcode>
                   2392: tag. It goes through all the states and elements, executing the <finalcode>
                   2393: snippets and collecting the results. Finally, it takes the user out of the
                   2394: helper, going to a provided page.
                   2395: 
                   2396: =cut
                   2397: 
                   2398: no strict;
                   2399: @ISA = ("Apache::lonhelper::element");
                   2400: use strict;
                   2401: 
                   2402: BEGIN {
                   2403:     &Apache::lonhelper::register('Apache::lonhelper::final',
                   2404:                                  ('final', 'exitpage'));
                   2405: }
                   2406: 
                   2407: sub new {
                   2408:     my $ref = Apache::lonhelper::element->new();
                   2409:     bless($ref);
                   2410: }
                   2411: 
                   2412: sub start_final { return ''; }
                   2413: 
                   2414: sub end_final {
                   2415:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2416: 
                   2417:     if ($target ne 'helper') {
                   2418:         return '';
                   2419:     }
                   2420: 
                   2421:     Apache::lonhelper::final->new();
                   2422:    
                   2423:     return '';
                   2424: }
                   2425: 
                   2426: sub start_exitpage {
                   2427:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2428: 
                   2429:     if ($target ne 'helper') {
                   2430:         return '';
                   2431:     }
                   2432: 
                   2433:     $paramHash->{EXIT_PAGE} = &Apache::lonxml::get_all_text('/exitpage',
                   2434:                                                             $parser);
                   2435: 
                   2436:     return '';
                   2437: }
                   2438: 
                   2439: sub end_exitpage { return ''; }
                   2440: 
                   2441: sub render {
                   2442:     my $self = shift;
                   2443: 
                   2444:     my @results;
                   2445: 
                   2446:     # Collect all the results
                   2447:     for my $stateName (keys %{$helper->{STATES}}) {
                   2448:         my $state = $helper->{STATES}->{$stateName};
                   2449:         
                   2450:         for my $element (@{$state->{ELEMENTS}}) {
                   2451:             if (defined($element->{FINAL_CODE})) {
                   2452:                 # Compile the code.
1.31      bowersj2 2453:                 my $code = 'sub { my $helper = shift; my $element = shift; ' 
                   2454:                     . $element->{FINAL_CODE} . '}';
1.27      bowersj2 2455:                 $code = eval($code);
                   2456:                 die 'Error while executing final code for element with var ' .
                   2457:                     $element->{'variable'} . ', Perl said: ' . $@ if $@;
                   2458: 
1.31      bowersj2 2459:                 my $result = &$code($helper, $element);
1.27      bowersj2 2460:                 if ($result) {
                   2461:                     push @results, $result;
                   2462:                 }
                   2463:             }
                   2464:         }
                   2465:     }
                   2466: 
                   2467:     if (scalar(@results) == 0) {
                   2468:         return '';
                   2469:     }
                   2470: 
                   2471:     my $result = "<ul>\n";
                   2472:     for my $re (@results) {
                   2473:         $result .= '    <li>' . $re . "</li>\n";
                   2474:     }
                   2475:     return $result . '</ul>';
                   2476: }
                   2477: 
                   2478: 1;
                   2479: 
1.13      bowersj2 2480: package Apache::lonhelper::parmwizfinal;
                   2481: 
                   2482: # This is the final state for the parmwizard. It is not generally useful,
                   2483: # so it is not perldoc'ed. It does its own processing.
                   2484: # It is represented with <parmwizfinal />, and
                   2485: # should later be moved to lonparmset.pm .
                   2486: 
                   2487: no strict;
                   2488: @ISA = ('Apache::lonhelper::element');
                   2489: use strict;
1.11      bowersj2 2490: 
1.13      bowersj2 2491: BEGIN {
                   2492:     &Apache::lonhelper::register('Apache::lonhelper::parmwizfinal',
                   2493:                                  ('parmwizfinal'));
                   2494: }
                   2495: 
                   2496: use Time::localtime;
                   2497: 
                   2498: sub new {
                   2499:     my $ref = Apache::lonhelper::choices->new();
                   2500:     bless ($ref);
                   2501: }
                   2502: 
                   2503: sub start_parmwizfinal { return ''; }
                   2504: 
                   2505: sub end_parmwizfinal {
                   2506:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2507: 
                   2508:     if ($target ne 'helper') {
                   2509:         return '';
                   2510:     }
                   2511:     Apache::lonhelper::parmwizfinal->new();
                   2512: }
                   2513: 
                   2514: # Renders a form that, when submitted, will form the input to lonparmset.pm
                   2515: sub render {
                   2516:     my $self = shift;
                   2517:     my $vars = $helper->{VARS};
                   2518: 
                   2519:     # FIXME: Unify my designators with the standard ones
                   2520:     my %dateTypeHash = ('open_date' => "Opening Date",
                   2521:                         'due_date' => "Due Date",
                   2522:                         'answer_date' => "Answer Date");
                   2523:     my %parmTypeHash = ('open_date' => "0_opendate",
                   2524:                         'due_date' => "0_duedate",
                   2525:                         'answer_date' => "0_answerdate");
                   2526:     
                   2527:     my $affectedResourceId = "";
                   2528:     my $parm_name = $parmTypeHash{$vars->{ACTION_TYPE}};
                   2529:     my $level = "";
1.27      bowersj2 2530:     my $resourceString;
                   2531:     my $symb;
                   2532:     my $paramlevel;
                   2533: 
1.13      bowersj2 2534:     # Print the granularity, depending on the action
                   2535:     if ($vars->{GRANULARITY} eq 'whole_course') {
1.27      bowersj2 2536:         $resourceString .= '<li>for <b>all resources in the course</b></li>';
1.13      bowersj2 2537:         $level = 9; # general course, see lonparmset.pm perldoc
                   2538:         $affectedResourceId = "0.0";
1.27      bowersj2 2539:         $symb = 'a';
                   2540:         $paramlevel = 'general';
1.13      bowersj2 2541:     } elsif ($vars->{GRANULARITY} eq 'map') {
                   2542:         my $navmap = Apache::lonnavmaps::navmap->new(
                   2543:                            $ENV{"request.course.fn"}.".db",
                   2544:                            $ENV{"request.course.fn"}."_parms.db", 0, 0);
                   2545:         my $res = $navmap->getById($vars->{RESOURCE_ID});
                   2546:         my $title = $res->compTitle();
1.27      bowersj2 2547:         $symb = $res->symb();
1.13      bowersj2 2548:         $navmap->untieHashes();
1.27      bowersj2 2549:         $resourceString .= "<li>for the map named <b>$title</b></li>";
1.13      bowersj2 2550:         $level = 8;
                   2551:         $affectedResourceId = $vars->{RESOURCE_ID};
1.27      bowersj2 2552:         $paramlevel = 'map';
1.13      bowersj2 2553:     } else {
                   2554:         my $navmap = Apache::lonnavmaps::navmap->new(
                   2555:                            $ENV{"request.course.fn"}.".db",
                   2556:                            $ENV{"request.course.fn"}."_parms.db", 0, 0);
                   2557:         my $res = $navmap->getById($vars->{RESOURCE_ID});
1.27      bowersj2 2558:         $symb = $res->symb();
1.13      bowersj2 2559:         my $title = $res->compTitle();
                   2560:         $navmap->untieHashes();
1.27      bowersj2 2561:         $resourceString .= "<li>for the resource named <b>$title</b></li>";
1.13      bowersj2 2562:         $level = 7;
                   2563:         $affectedResourceId = $vars->{RESOURCE_ID};
1.27      bowersj2 2564:         $paramlevel = 'full';
1.13      bowersj2 2565:     }
                   2566: 
1.27      bowersj2 2567:     my $result = "<form name='helpform' method='get' action='/adm/parmset#$affectedResourceId&$parm_name&$level'>\n";
                   2568:     $result .= '<p>Confirm that this information is correct, then click &quot;Finish Wizard&quot; to complete setting the parameter.<ul>';
                   2569:     
                   2570:     # Print the type of manipulation:
                   2571:     $result .= '<li>Setting the <b>' . $dateTypeHash{$vars->{ACTION_TYPE}}
                   2572:                . "</b></li>\n";
                   2573:     if ($vars->{ACTION_TYPE} eq 'due_date' || 
                   2574:         $vars->{ACTION_TYPE} eq 'answer_date') {
                   2575:         # for due dates, we default to "date end" type entries
                   2576:         $result .= "<input type='hidden' name='recent_date_end' " .
                   2577:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2578:         $result .= "<input type='hidden' name='pres_value' " . 
                   2579:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2580:         $result .= "<input type='hidden' name='pres_type' " .
                   2581:             "value='date_end' />\n";
                   2582:     } elsif ($vars->{ACTION_TYPE} eq 'open_date') {
                   2583:         $result .= "<input type='hidden' name='recent_date_start' ".
                   2584:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2585:         $result .= "<input type='hidden' name='pres_value' " .
                   2586:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   2587:         $result .= "<input type='hidden' name='pres_type' " .
                   2588:             "value='date_start' />\n";
                   2589:     } 
                   2590: 
                   2591:     $result .= $resourceString;
                   2592:     
1.13      bowersj2 2593:     # Print targets
                   2594:     if ($vars->{TARGETS} eq 'course') {
                   2595:         $result .= '<li>for <b>all students in course</b></li>';
                   2596:     } elsif ($vars->{TARGETS} eq 'section') {
                   2597:         my $section = $vars->{SECTION_NAME};
                   2598:         $result .= "<li>for section <b>$section</b></li>";
                   2599:         $level -= 3;
                   2600:         $result .= "<input type='hidden' name='csec' value='" .
                   2601:             HTML::Entities::encode($section) . "' />\n";
                   2602:     } else {
                   2603:         # FIXME: This is probably wasteful! Store the name!
                   2604:         my $classlist = Apache::loncoursedata::get_classlist();
1.27      bowersj2 2605:         my $username = $vars->{USER_NAME};
                   2606:         # Chop off everything after the last colon (section)
                   2607:         $username = substr($username, 0, rindex($username, ':'));
                   2608:         my $name = $classlist->{$username}->[6];
1.13      bowersj2 2609:         $result .= "<li>for <b>$name</b></li>";
                   2610:         $level -= 6;
                   2611:         my ($uname, $udom) = split /:/, $vars->{USER_NAME};
                   2612:         $result .= "<input type='hidden' name='uname' value='".
                   2613:             HTML::Entities::encode($uname) . "' />\n";
                   2614:         $result .= "<input type='hidden' name='udom' value='".
                   2615:             HTML::Entities::encode($udom) . "' />\n";
                   2616:     }
                   2617: 
                   2618:     # Print value
                   2619:     $result .= "<li>to <b>" . ctime($vars->{PARM_DATE}) . "</b> (" .
                   2620:         Apache::lonnavmaps::timeToHumanString($vars->{PARM_DATE}) 
                   2621:         . ")</li>\n";
                   2622: 
                   2623:     # print pres_marker
                   2624:     $result .= "\n<input type='hidden' name='pres_marker'" .
                   2625:         " value='$affectedResourceId&$parm_name&$level' />\n";
1.27      bowersj2 2626:     
                   2627:     # Make the table appear
                   2628:     $result .= "\n<input type='hidden' value='true' name='prevvisit' />";
                   2629:     $result .= "\n<input type='hidden' value='all' name='pschp' />";
                   2630:     $result .= "\n<input type='hidden' value='$symb' name='pssymb' />";
                   2631:     $result .= "\n<input type='hidden' value='$paramlevel' name='parmlev' />";
1.13      bowersj2 2632: 
                   2633:     $result .= "<br /><br /><center><input type='submit' value='Finish Helper' /></center></form>\n";
                   2634: 
                   2635:     return $result;
                   2636: }
                   2637:     
                   2638: sub overrideForm {
                   2639:     return 1;
                   2640: }
1.5       bowersj2 2641: 
1.4       bowersj2 2642: 1;
1.3       bowersj2 2643: 
1.1       bowersj2 2644: __END__
1.3       bowersj2 2645: 

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