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

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

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