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

1.1       bowersj2    1: # The LearningOnline Network with CAPA
                      2: # .helper XML handler to implement the LON-CAPA helper
                      3: #
1.196   ! raeburn     4: # $Id: lonhelper.pm,v 1.195 2015/08/15 20:11:57 raeburn 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: 
1.3       bowersj2   29: =pod
                     30: 
1.44      bowersj2   31: =head1 NAME
1.3       bowersj2   32: 
1.44      bowersj2   33: lonhelper - implements helper framework
                     34: 
                     35: =head1 SYNOPSIS
                     36: 
                     37: lonhelper implements the helper framework for LON-CAPA, and provides
                     38:     many generally useful components for that framework.
                     39: 
                     40: Helpers are little programs which present the user with a sequence of
                     41:     simple choices, instead of one monolithic multi-dimensional
                     42:     choice. They are also referred to as "wizards", "druids", and
                     43:     other potentially trademarked or semantically-loaded words.
                     44: 
                     45: =head1 OVERVIEWX<lonhelper>
                     46: 
                     47: Helpers are well-established UI widgets that users
1.3       bowersj2   48: feel comfortable with. It can take a complicated multidimensional problem the
                     49: user has and turn it into a series of bite-sized one-dimensional questions.
                     50: 
                     51: For developers, helpers provide an easy way to bundle little bits of functionality
                     52: for the user, without having to write the tedious state-maintenence code.
                     53: 
                     54: Helpers are defined as XML documents, placed in the /home/httpd/html/adm/helpers 
                     55: directory and having the .helper file extension. For examples, see that directory.
                     56: 
                     57: All classes are in the Apache::lonhelper namespace.
                     58: 
1.44      bowersj2   59: =head1 lonhelper XML file formatX<lonhelper, XML file format>
1.3       bowersj2   60: 
                     61: A helper consists of a top-level <helper> tag which contains a series of states.
                     62: Each state contains one or more state elements, which are what the user sees, like
                     63: messages, resource selections, or date queries.
                     64: 
                     65: The helper tag is required to have one attribute, "title", which is the name
1.31      bowersj2   66: of the helper itself, such as "Parameter helper". The helper tag may optionally
1.195     raeburn    67: have a "requiredpriv" attribute, specifying the privilege a user must have
1.31      bowersj2   68: to use the helper, or get denied access. See loncom/auth/rolesplain.tab for
1.195     raeburn    69: useful privs. You may add the modifier &S at the end of the three letter priv
                     70: if you want to grant access to users for whom the corresponding privilege is 
                     71: section-specific. The default is full access, which is often wrong!
1.3       bowersj2   72: 
                     73: =head2 State tags
                     74: 
                     75: State tags are required to have an attribute "name", which is the symbolic
1.7       bowersj2   76: name of the state and will not be directly seen by the user. The helper is
                     77: required to have one state named "START", which is the state the helper
1.5       bowersj2   78: will start with. By convention, this state should clearly describe what
1.3       bowersj2   79: the helper will do for the user, and may also include the first information
                     80: entry the user needs to do for the helper.
                     81: 
                     82: State tags are also required to have an attribute "title", which is the
                     83: human name of the state, and will be displayed as the header on top of 
                     84: the screen for the user.
                     85: 
1.160     albertel   86: State tags may also optionally have an attribute "help" which should be
                     87: the filename of a help file, this will add a blue ? to the title.
                     88: 
1.3       bowersj2   89: =head2 Example Helper Skeleton
                     90: 
                     91: An example of the tags so far:
                     92: 
                     93:  <helper title="Example Helper">
                     94:    <state name="START" title="Demonstrating the Example Helper">
1.160     albertel   95:      <!-- notice this is the START state the helper requires -->
1.3       bowersj2   96:      </state>
                     97:    <state name="GET_NAME" title="Enter Student Name">
                     98:      </state>
                     99:    </helper>
                    100: 
1.160     albertel  101: Of course this does nothing. In order for the helper to do something, it is
                    102: necessary to put actual elements into the helper. Documentation for each
1.3       bowersj2  103: of these elements follows.
                    104: 
1.44      bowersj2  105: =head1 Creating a Helper With Code, Not XML
1.13      bowersj2  106: 
1.160     albertel  107: In some situations, such as the printing helper (see lonprintout.pm), 
1.13      bowersj2  108: writing the helper in XML would be too complicated, because of scope 
                    109: issues or the fact that the code actually outweighs the XML. It is
                    110: possible to create a helper via code, though it is a little odd.
                    111: 
                    112: Creating a helper via code is more like issuing commands to create
                    113: a helper then normal code writing. For instance, elements will automatically
                    114: be added to the last state created, so it's important to create the 
                    115: states in the correct order.
                    116: 
                    117: First, create a new helper:
                    118: 
                    119:  use Apache::lonhelper;
                    120: 
                    121:  my $helper = Apache::lonhelper::new->("Helper Title");
                    122: 
                    123: Next you'll need to manually add states to the helper:
                    124: 
                    125:  Apache::lonhelper::state->new("STATE_NAME", "State's Human Title");
                    126: 
                    127: You don't need to save a reference to it because all elements up until
                    128: the next state creation will automatically be added to this state.
                    129: 
                    130: Elements are created by populating the $paramHash in 
                    131: Apache::lonhelper::paramhash. To prevent namespace issues, retrieve 
                    132: a reference to that has with getParamHash:
                    133: 
                    134:  my $paramHash = Apache::lonhelper::getParamHash();
                    135: 
                    136: You will need to do this for each state you create.
                    137: 
                    138: Populate the $paramHash with the parameters for the element you wish
                    139: to add next; the easiest way to find out what those entries are is
                    140: to read the code. Some common ones are 'variable' to record the variable
                    141: to store the results in, and NEXTSTATE to record a next state transition.
                    142: 
                    143: Then create your element:
                    144: 
                    145:  $paramHash->{MESSAGETEXT} = "This is a message.";
                    146:  Apache::lonhelper::message->new();
                    147: 
                    148: The creation will take the $paramHash and bless it into a
                    149: Apache::lonhelper::message object. To create the next element, you need
                    150: to get a reference to the new, empty $paramHash:
                    151: 
                    152:  $paramHash = Apache::lonhelper::getParamHash();
                    153: 
                    154: and you can repeat creating elements that way. You can add states
                    155: and elements as needed.
                    156: 
                    157: See lonprintout.pm, subroutine printHelper for an example of this, where
                    158: we dynamically add some states to prevent security problems, for instance.
                    159: 
                    160: Normally the machinery in the XML format is sufficient; dynamically 
                    161: adding states can easily be done by wrapping the state in a <condition>
                    162: tag. This should only be used when the code dominates the XML content,
                    163: the code is so complicated that it is difficult to get access to
1.44      bowersj2  164: all of the information you need because of scoping issues, or would-be <exec> or 
                    165: <eval> blocks using the {DATA} mechanism results in hard-to-read
                    166: and -maintain code. (See course.initialization.helper for a borderline
                    167: case.)
1.13      bowersj2  168: 
                    169: It is possible to do some of the work with an XML fragment parsed by
1.17      bowersj2  170: lonxml; again, see lonprintout.pm for an example. In that case it is 
                    171: imperative that you call B<Apache::lonhelper::registerHelperTags()>
                    172: before parsing XML fragments and B<Apache::lonhelper::unregisterHelperTags()>
                    173: when you are done. See lonprintout.pm for examples of this usage in the
                    174: printHelper subroutine.
1.13      bowersj2  175: 
1.57      albertel  176: =head2 Localization
                    177: 
                    178: The helper framework tries to handle as much localization as
                    179: possible. The text is always run through
                    180: Apache::lonlocal::normalize_string, so be sure to run the keys through
                    181: that function for maximum usefulness and robustness.
                    182: 
1.3       bowersj2  183: =cut
                    184: 
1.1       bowersj2  185: package Apache::lonhelper;
1.2       bowersj2  186: use Apache::Constants qw(:common);
                    187: use Apache::File;
1.3       bowersj2  188: use Apache::lonxml;
1.57      albertel  189: use Apache::lonlocal;
1.100     albertel  190: use Apache::lonnet;
1.151     raeburn   191: use Apache::longroup;
1.148     foxr      192: use Apache::lonselstudent;
1.171     foxr      193: 
                    194: 
1.152     www       195: use LONCAPA;
1.139     foxr      196: 
1.7       bowersj2  197: # Register all the tags with the helper, so the helper can 
                    198: # push and pop them
                    199: 
                    200: my @helperTags;
                    201: 
                    202: sub register {
                    203:     my ($namespace, @tags) = @_;
                    204: 
                    205:     for my $tag (@tags) {
                    206:         push @helperTags, [$namespace, $tag];
                    207:     }
                    208: }
                    209: 
1.2       bowersj2  210: BEGIN {
1.7       bowersj2  211:     Apache::lonxml::register('Apache::lonhelper', 
                    212:                              ('helper'));
                    213:       register('Apache::lonhelper', ('state'));
1.2       bowersj2  214: }
                    215: 
1.7       bowersj2  216: # Since all helpers are only three levels deep (helper tag, state tag, 
1.3       bowersj2  217: # substate type), it's easier and more readble to explicitly track 
                    218: # those three things directly, rather then futz with the tag stack 
                    219: # every time.
                    220: my $helper;
                    221: my $state;
                    222: my $substate;
1.4       bowersj2  223: # To collect parameters, the contents of the subtags are collected
                    224: # into this paramHash, then passed to the element object when the 
                    225: # end of the element tag is located.
                    226: my $paramHash; 
1.2       bowersj2  227: 
1.25      bowersj2  228: # Note from Jeremy 5-8-2003: It is *vital* that the real handler be called
                    229: # as a subroutine from the handler, or very mysterious things might happen.
                    230: # I don't know exactly why, but it seems that the scope where the Apache
                    231: # server enters the perl handler is treated differently from the rest of
                    232: # the handler. This also seems to manifest itself in the debugger as entering
                    233: # the perl handler in seemingly random places (sometimes it starts in the
                    234: # compiling phase, sometimes in the handler execution phase where it runs
                    235: # the code and stepping into the "1;" the module ends with goes into the handler,
                    236: # sometimes starting directly with the handler); I think the cause is related.
                    237: # In the debugger, this means that breakpoints are ignored until you step into
                    238: # a function and get out of what must be a "faked up scope" in the Apache->
                    239: # mod_perl connection. In this code, it was manifesting itself in the existence
1.65      www       240: # of two separate file-scoped $helper variables, one set to the value of the
1.25      bowersj2  241: # helper in the helper constructor, and one referenced by the handler on the
1.44      bowersj2  242: # "$helper->process()" line. Using the debugger, one could actually
                    243: # see the two different $helper variables, as hashes at completely
                    244: # different addresses. The second was therefore never set, and was still
1.25      bowersj2  245: # undefined when I tried to call process on it.
                    246: # By pushing the "real handler" down into the "real scope", everybody except the 
                    247: # actual handler function directly below this comment gets the same $helper and
                    248: # everybody is happy.
                    249: # The upshot of all of this is that for safety when a handler is  using 
                    250: # file-scoped variables in LON-CAPA, the handler should be pushed down one 
                    251: # call level, as I do here, to ensure that the top-level handler function does
                    252: # not get a different file scope from the rest of the code.
                    253: sub handler {
                    254:     my $r = shift;
                    255:     return real_handler($r);
                    256: }
                    257: 
1.13      bowersj2  258: # For debugging purposes, one can send a second parameter into this
                    259: # function, the 'uri' of the helper you wish to have rendered, and
                    260: # call this from other handlers.
1.25      bowersj2  261: sub real_handler {
1.3       bowersj2  262:     my $r = shift;
1.13      bowersj2  263:     my $uri = shift;
                    264:     if (!defined($uri)) { $uri = $r->uri(); }
1.100     albertel  265:     $env{'request.uri'} = $uri;
1.187     raeburn   266:     my $filename = $r->dir_config('lonDocRoot').$uri;
1.2       bowersj2  267:     my $fh = Apache::File->new($filename);
                    268:     my $file;
1.3       bowersj2  269:     read $fh, $file, 100000000;
                    270: 
1.27      bowersj2  271: 
1.3       bowersj2  272:     # Send header, don't cache this page
1.100     albertel  273:     if ($env{'browser.mathml'}) {
1.70      sakharuk  274: 	&Apache::loncommon::content_type($r,'text/xml');
                    275:     } else {
                    276: 	&Apache::loncommon::content_type($r,'text/html');
                    277:     }
                    278:     $r->send_http_header;
                    279:     return OK if $r->header_only;
1.3       bowersj2  280:     $r->rflush();
1.2       bowersj2  281: 
1.3       bowersj2  282:     # Discard result, we just want the objects that get created by the
                    283:     # xml parsing
                    284:     &Apache::lonxml::xmlparse($r, 'helper', $file);
1.2       bowersj2  285: 
1.31      bowersj2  286:     my $allowed = $helper->allowedCheck();
                    287:     if (!$allowed) {
1.195     raeburn   288:         my ($priv,$modifier) = split(/\&/,$helper->{REQUIRED_PRIV});
                    289:         $env{'user.error.msg'} = $env{'request.uri'}.':'.$priv.
1.31      bowersj2  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'},
1.160     albertel  345:                                   $token->[2]{'title'},
                    346: 				  $token->[2]{'help'});
1.3       bowersj2  347:     return '';
                    348: }
                    349: 
1.13      bowersj2  350: # Use this to get the param hash from other files.
                    351: sub getParamHash {
                    352:     return $paramHash;
                    353: }
                    354: 
                    355: # Use this to get the helper, if implementing elements in other files
                    356: # (like lonprintout.pm)
                    357: sub getHelper {
                    358:     return $helper;
                    359: }
                    360: 
1.3       bowersj2  361: # don't need this, so ignore it
                    362: sub end_state {
                    363:     return '';
                    364: }
                    365: 
1.1       bowersj2  366: 1;
                    367: 
1.3       bowersj2  368: package Apache::lonhelper::helper;
                    369: 
                    370: use Digest::MD5 qw(md5_hex);
1.57      albertel  371: use HTML::Entities();
1.3       bowersj2  372: use Apache::loncommon;
                    373: use Apache::File;
1.57      albertel  374: use Apache::lonlocal;
1.100     albertel  375: use Apache::lonnet;
1.154     albertel  376: use LONCAPA;
1.3       bowersj2  377: 
                    378: sub new {
                    379:     my $proto = shift;
                    380:     my $class = ref($proto) || $proto;
                    381:     my $self = {};
                    382: 
                    383:     $self->{TITLE} = shift;
1.31      bowersj2  384:     $self->{REQUIRED_PRIV} = shift;
1.3       bowersj2  385:     
                    386:     # If there is a state from the previous form, use that. If there is no
                    387:     # state, use the start state parameter.
1.100     albertel  388:     if (defined $env{"form.CURRENT_STATE"})
1.3       bowersj2  389:     {
1.100     albertel  390: 	$self->{STATE} = $env{"form.CURRENT_STATE"};
1.3       bowersj2  391:     }
                    392:     else
                    393:     {
                    394: 	$self->{STATE} = "START";
                    395:     }
                    396: 
1.100     albertel  397:     $self->{TOKEN} = $env{'form.TOKEN'};
1.3       bowersj2  398:     # If a token was passed, we load that in. Otherwise, we need to create a 
                    399:     # new storage file
                    400:     # Tried to use standard Tie'd hashes, but you can't seem to take a 
                    401:     # reference to a tied hash and write to it. I'd call that a wart.
                    402:     if ($self->{TOKEN}) {
                    403:         # Validate the token before trusting it
                    404:         if ($self->{TOKEN} !~ /^[a-f0-9]{32}$/) {
                    405:             # Not legit. Return nothing and let all hell break loose.
                    406:             # User shouldn't be doing that!
                    407:             return undef;
                    408:         }
                    409: 
                    410:         # Get the hash.
                    411:         $self->{FILENAME} = $Apache::lonnet::tmpdir . md5_hex($self->{TOKEN}); # Note the token is not the literal file
                    412:         
                    413:         my $file = Apache::File->new($self->{FILENAME});
                    414:         my $contents = <$file>;
1.5       bowersj2  415: 
                    416:         # Now load in the contents
                    417:         for my $value (split (/&/, $contents)) {
                    418:             my ($name, $value) = split(/=/, $value);
                    419:             $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
                    420:             $self->{VARS}->{$name} = $value;
                    421:         }
                    422: 
1.3       bowersj2  423:         $file->close();
                    424:     } else {
                    425:         # Only valid if we're just starting.
                    426:         if ($self->{STATE} ne 'START') {
                    427:             return undef;
                    428:         }
                    429:         # Must create the storage
1.100     albertel  430:         $self->{TOKEN} = md5_hex($env{'user.name'} . $env{'user.domain'} .
1.3       bowersj2  431:                                  time() . rand());
                    432:         $self->{FILENAME} = $Apache::lonnet::tmpdir . md5_hex($self->{TOKEN});
                    433:     }
                    434: 
                    435:     # OK, we now have our persistent storage.
                    436: 
1.100     albertel  437:     if (defined $env{"form.RETURN_PAGE"})
1.3       bowersj2  438:     {
1.100     albertel  439: 	$self->{RETURN_PAGE} = $env{"form.RETURN_PAGE"};
1.3       bowersj2  440:     }
                    441:     else
                    442:     {
                    443: 	$self->{RETURN_PAGE} = $ENV{REFERER};
                    444:     }
                    445: 
                    446:     $self->{STATES} = {};
                    447:     $self->{DONE} = 0;
                    448: 
1.9       bowersj2  449:     # Used by various helpers for various things; see lonparm.helper
                    450:     # for an example.
                    451:     $self->{DATA} = {};
                    452: 
1.13      bowersj2  453:     $helper = $self;
                    454: 
                    455:     # Establish the $paramHash
                    456:     $paramHash = {};
                    457: 
1.3       bowersj2  458:     bless($self, $class);
                    459:     return $self;
                    460: }
                    461: 
                    462: # Private function; returns a string to construct the hidden fields
                    463: # necessary to have the helper track state.
                    464: sub _saveVars {
                    465:     my $self = shift;
                    466:     my $result = "";
                    467:     $result .= '<input type="hidden" name="CURRENT_STATE" value="' .
1.67      albertel  468:         HTML::Entities::encode($self->{STATE},'<>&"') . "\" />\n";
1.3       bowersj2  469:     $result .= '<input type="hidden" name="TOKEN" value="' .
                    470:         $self->{TOKEN} . "\" />\n";
                    471:     $result .= '<input type="hidden" name="RETURN_PAGE" value="' .
1.67      albertel  472:         HTML::Entities::encode($self->{RETURN_PAGE},'<>&"') . "\" />\n";
1.3       bowersj2  473: 
                    474:     return $result;
                    475: }
                    476: 
                    477: # Private function: Create the querystring-like representation of the stored
                    478: # data to write to disk.
                    479: sub _varsInFile {
                    480:     my $self = shift;
                    481:     my @vars = ();
1.154     albertel  482:     for my $key (keys(%{$self->{VARS}})) {
                    483:         push(@vars, &escape($key) . '=' . &escape($self->{VARS}->{$key}));
1.3       bowersj2  484:     }
                    485:     return join ('&', @vars);
                    486: }
                    487: 
1.5       bowersj2  488: # Use this to declare variables.
                    489: # FIXME: Document this
                    490: sub declareVar {
                    491:     my $self = shift;
                    492:     my $var = shift;
                    493: 
                    494:     if (!defined($self->{VARS}->{$var})) {
                    495:         $self->{VARS}->{$var} = '';
                    496:     }
                    497: 
1.157     raeburn   498:     my $envname = 'form.' . $var . '_forminput';
1.100     albertel  499:     if (defined($env{$envname})) {
                    500:         if (ref($env{$envname})) {
                    501:             $self->{VARS}->{$var} = join('|||', @{$env{$envname}});
1.28      bowersj2  502:         } else {
1.100     albertel  503:             $self->{VARS}->{$var} = $env{$envname};
1.28      bowersj2  504:         }
1.5       bowersj2  505:     }
                    506: }
                    507: 
1.31      bowersj2  508: sub allowedCheck {
                    509:     my $self = shift;
                    510: 
                    511:     if (!defined($self->{REQUIRED_PRIV})) { 
                    512:         return 1;
                    513:     }
1.195     raeburn   514:     my ($priv,$modifier) = split(/\&/,$self->{REQUIRED_PRIV});
                    515:     my $allowed = &Apache::lonnet::allowed($priv,$env{'request.course.id'});
                    516:     if ((!$allowed) && ($modifier eq 'S') && ($env{'request.course.sec'} ne '')) {
                    517:         $allowed = &Apache::lonnet::allowed($priv,$env{'request.course.id'}.'/'.
                    518:                                                   $env{'request.course.sec'});
                    519:     }
                    520:     return $allowed;
1.31      bowersj2  521: }
                    522: 
1.3       bowersj2  523: sub changeState {
                    524:     my $self = shift;
                    525:     $self->{STATE} = shift;
                    526: }
                    527: 
                    528: sub registerState {
                    529:     my $self = shift;
                    530:     my $state = shift;
                    531: 
                    532:     my $stateName = $state->name();
                    533:     $self->{STATES}{$stateName} = $state;
                    534: }
                    535: 
1.13      bowersj2  536: sub process {
1.3       bowersj2  537:     my $self = shift;
                    538: 
                    539:     # Phase 1: Post processing for state of previous screen (which is actually
                    540:     # the "current state" in terms of the helper variables), if it wasn't the 
                    541:     # beginning state.
1.170     schafran  542:     if ($self->{STATE} ne "START" || $env{"form.SUBMIT"} eq &mt("Next")) {
1.3       bowersj2  543: 	my $prevState = $self->{STATES}{$self->{STATE}};
1.13      bowersj2  544:         $prevState->postprocess();
1.3       bowersj2  545:     }
                    546:     
                    547:     # Note, to handle errors in a state's input that a user must correct,
                    548:     # do not transition in the postprocess, and force the user to correct
                    549:     # the error.
                    550: 
                    551:     # Phase 2: Preprocess current state
                    552:     my $startState = $self->{STATE};
1.17      bowersj2  553:     my $state = $self->{STATES}->{$startState};
1.3       bowersj2  554:     
1.13      bowersj2  555:     # For debugging, print something here to determine if you're going
                    556:     # to an undefined state.
1.3       bowersj2  557:     if (!defined($state)) {
1.13      bowersj2  558:         return;
1.3       bowersj2  559:     }
                    560:     $state->preprocess();
                    561: 
                    562:     # Phase 3: While the current state is different from the previous state,
                    563:     # keep processing.
1.17      bowersj2  564:     while ( $startState ne $self->{STATE} && 
                    565:             defined($self->{STATES}->{$self->{STATE}}) )
1.3       bowersj2  566:     {
                    567: 	$startState = $self->{STATE};
1.17      bowersj2  568: 	$state = $self->{STATES}->{$startState};
1.3       bowersj2  569: 	$state->preprocess();
                    570:     }
                    571: 
1.13      bowersj2  572:     return;
                    573: } 
                    574: 
                    575: # 1: Do the post processing for the previous state.
                    576: # 2: Do the preprocessing for the current state.
                    577: # 3: Check to see if state changed, if so, postprocess current and move to next.
                    578: #    Repeat until state stays stable.
                    579: # 4: Render the current state to the screen as an HTML page.
                    580: sub display {
                    581:     my $self = shift;
1.181     raeburn   582:     my $footer = shift;
1.13      bowersj2  583:     my $state = $self->{STATES}{$self->{STATE}};
                    584: 
                    585:     my $result = "";
                    586: 
1.17      bowersj2  587:     if (!defined($state)) {
                    588:         $result = "<font color='#ff0000'>Error: state '$state' not defined!</font>";
                    589:         return $result;
                    590:     }
                    591: 
1.3       bowersj2  592:     # Phase 4: Display.
1.68      sakharuk  593:     my $stateTitle=&mt($state->title());
1.160     albertel  594:     my $stateHelp=     $state->help();
1.135     albertel  595:     my $browser_searcher_js = 
                    596: 	'<script type="text/javascript">'."\n".
                    597: 	&Apache::loncommon::browser_and_searcher_javascript().
                    598: 	"\n".'</script>';
                    599: 
1.174     bisitz    600:     # Breadcrumbs
                    601:     my $brcrum = [{'href' => '',
                    602:                    'text' => 'Helper'}];
                    603:     # FIXME: Dynamically add context sensitive breadcrumbs
                    604:     #        depending on the caller,
                    605:     #        e.g. printing, parametrization, etc.
                    606:     # FIXME: Add breadcrumbs to reflect current helper state
                    607: 
1.135     albertel  608:     $result .= &Apache::loncommon::start_page($self->{TITLE},
1.174     bisitz    609:                                               $browser_searcher_js,
                    610:                                               {'bread_crumbs' => $brcrum,});
                    611: 
1.170     schafran  612:     my $previous = HTML::Entities::encode(&mt("Back"), '<>&"');
                    613:     my $next = HTML::Entities::encode(&mt("Next"), '<>&"');
1.57      albertel  614:     # FIXME: This should be parameterized, not concatenated - Jeremy
1.3       bowersj2  615: 
1.135     albertel  616: 
1.181     raeburn   617:     if (!$state->overrideForm()) { $result.='<form name="helpform" method="post" action="">'; }
1.160     albertel  618:     if ($stateHelp) {
1.175     bisitz    619:         $stateHelp = &Apache::loncommon::help_open_topic($stateHelp);
1.160     albertel  620:     }
1.3       bowersj2  621: 
1.175     bisitz    622:     # Prepare buttons
                    623:     my $buttons;
1.3       bowersj2  624:     if (!$state->overrideForm()) {
                    625:         if ($self->{STATE} ne $self->{START_STATE}) {
                    626:             #$result .= '<input name="SUBMIT" type="submit" value="&lt;- Previous" />&nbsp;&nbsp;';
                    627:         }
1.175     bisitz    628:         $buttons = '<p>'; # '<fieldset>';
1.3       bowersj2  629:         if ($self->{DONE}) {
                    630:             my $returnPage = $self->{RETURN_PAGE};
1.175     bisitz    631:             $buttons .= '<a href="'.$returnPage.'">'.&mt('End Helper').'</a>';
1.3       bowersj2  632:         }
                    633:         else {
1.175     bisitz    634:             $buttons .= '<span class="LC_nobreak">'
                    635:                        .'<input name="back" type="button" '
                    636:                        .'value="'.$previous.'" onclick="history.go(-1)" /> '
                    637:                        .'<input name="SUBMIT" type="submit" value="'.$next.'" />'
                    638:                        .'</span>';
1.30      bowersj2  639:         }
1.175     bisitz    640:     $buttons .= '</p>'; # '</fieldset>';
1.30      bowersj2  641:     }
                    642: 
                    643: 
1.175     bisitz    644: 
                    645:     $result .= '<h2>'.$stateTitle.$stateHelp.'</h2>';
                    646: 
                    647: #   $result .= '<div>';
                    648: 
                    649:     # Top buttons
                    650:     $result .= $buttons;
                    651: 
                    652:     # Main content of current helper screen
1.30      bowersj2  653:     if (!$state->overrideForm()) {
1.175     bisitz    654:         $result .= $self->_saveVars();
1.3       bowersj2  655:     }
1.175     bisitz    656:     $result .= $state->render();
                    657: 
                    658:     # Bottom buttons
                    659:     $result .= $buttons;
                    660: 
1.3       bowersj2  661: 
1.193     raeburn   662:     #foreach my $key (keys(%{$self->{VARS}})) {
1.13      bowersj2  663:     #    $result .= "|$key| -> " . $self->{VARS}->{$key} . "<br />";
                    664:     #}
1.5       bowersj2  665: 
1.175     bisitz    666: #   $result .= '</div>';
1.30      bowersj2  667: 
1.3       bowersj2  668:     $result .= <<FOOTER;
                    669:         </form>
                    670: FOOTER
                    671: 
1.181     raeburn   672:     $result .= $footer.&Apache::loncommon::end_page();
1.3       bowersj2  673:     # Handle writing out the vars to the file
                    674:     my $file = Apache::File->new('>'.$self->{FILENAME});
1.33      bowersj2  675:     print $file $self->_varsInFile();
1.3       bowersj2  676: 
                    677:     return $result;
                    678: }
                    679: 
                    680: 1;
                    681: 
                    682: package Apache::lonhelper::state;
                    683: 
                    684: # States bundle things together and are responsible for compositing the
1.4       bowersj2  685: # various elements together. It is not generally necessary for users to
                    686: # use the state object directly, so it is not perldoc'ed.
                    687: 
                    688: # Basically, all the states do is pass calls to the elements and aggregate
                    689: # the results.
1.3       bowersj2  690: 
                    691: sub new {
                    692:     my $proto = shift;
                    693:     my $class = ref($proto) || $proto;
                    694:     my $self = {};
                    695: 
                    696:     $self->{NAME} = shift;
                    697:     $self->{TITLE} = shift;
1.160     albertel  698:     $self->{HELP} = shift;
1.3       bowersj2  699:     $self->{ELEMENTS} = [];
                    700: 
                    701:     bless($self, $class);
                    702: 
                    703:     $helper->registerState($self);
                    704: 
1.13      bowersj2  705:     $state = $self;
                    706: 
1.3       bowersj2  707:     return $self;
                    708: }
                    709: 
                    710: sub name {
                    711:     my $self = shift;
                    712:     return $self->{NAME};
                    713: }
                    714: 
                    715: sub title {
                    716:     my $self = shift;
                    717:     return $self->{TITLE};
                    718: }
                    719: 
1.160     albertel  720: sub help {
                    721:     my $self = shift;
                    722:     return $self->{HELP};
                    723: }
                    724: 
1.4       bowersj2  725: sub preprocess {
                    726:     my $self = shift;
                    727:     for my $element (@{$self->{ELEMENTS}}) {
                    728:         $element->preprocess();
                    729:     }
                    730: }
                    731: 
1.6       bowersj2  732: # FIXME: Document that all postprocesses must return a true value or
                    733: # the state transition will be overridden
1.4       bowersj2  734: sub postprocess {
                    735:     my $self = shift;
1.6       bowersj2  736: 
                    737:     # Save the state so we can roll it back if we need to.
                    738:     my $originalState = $helper->{STATE};
                    739:     my $everythingSuccessful = 1;
                    740: 
1.4       bowersj2  741:     for my $element (@{$self->{ELEMENTS}}) {
1.6       bowersj2  742:         my $result = $element->postprocess();
                    743:         if (!$result) { $everythingSuccessful = 0; }
                    744:     }
                    745: 
                    746:     # If not all the postprocesses were successful, override
                    747:     # any state transitions that may have occurred. It is the
                    748:     # responsibility of the states to make sure they have 
                    749:     # error handling in that case.
                    750:     if (!$everythingSuccessful) {
                    751:         $helper->{STATE} = $originalState;
1.4       bowersj2  752:     }
                    753: }
                    754: 
1.13      bowersj2  755: # Override the form if any element wants to.
                    756: # two elements overriding the form will make a mess, but that should
                    757: # be considered helper author error ;-)
1.4       bowersj2  758: sub overrideForm {
1.13      bowersj2  759:     my $self = shift;
                    760:     for my $element (@{$self->{ELEMENTS}}) {
                    761:         if ($element->overrideForm()) {
                    762:             return 1;
                    763:         }
                    764:     }
1.4       bowersj2  765:     return 0;
                    766: }
                    767: 
                    768: sub addElement {
                    769:     my $self = shift;
                    770:     my $element = shift;
                    771:     
                    772:     push @{$self->{ELEMENTS}}, $element;
                    773: }
                    774: 
                    775: sub render {
                    776:     my $self = shift;
                    777:     my @results = ();
                    778: 
                    779:     for my $element (@{$self->{ELEMENTS}}) {
                    780:         push @results, $element->render();
                    781:     }
1.28      bowersj2  782: 
1.4       bowersj2  783:     return join("\n", @results);
                    784: }
                    785: 
                    786: 1;
                    787: 
                    788: package Apache::lonhelper::element;
                    789: # Support code for elements
                    790: 
                    791: =pod
                    792: 
1.44      bowersj2  793: =head1 Element Base Class
1.4       bowersj2  794: 
1.28      bowersj2  795: The Apache::lonhelper::element base class provides support for elements
                    796: and defines some generally useful tags for use in elements.
1.4       bowersj2  797: 
1.44      bowersj2  798: =head2 finalcode tagX<finalcode>
1.25      bowersj2  799: 
                    800: Each element can contain a "finalcode" tag that, when the special FINAL
                    801: helper state is used, will be executed, surrounded by "sub { my $helper = shift;"
                    802: and "}". It is expected to return a string describing what it did, which 
                    803: may be an empty string. See course initialization helper for an example. This is
                    804: generally intended for helpers like the course initialization helper, which consist
                    805: of several panels, each of which is performing some sort of bite-sized functionality.
                    806: 
1.44      bowersj2  807: =head2 defaultvalue tagX<defaultvalue>
1.25      bowersj2  808: 
                    809: Each element that accepts user input can contain a "defaultvalue" tag that,
                    810: when surrounded by "sub { my $helper = shift; my $state = shift; " and "}",
                    811: will form a subroutine that when called will provide a default value for
                    812: the element. How this value is interpreted by the element is specific to
                    813: the element itself, and possibly the settings the element has (such as 
                    814: multichoice vs. single choice for <choices> tags). 
                    815: 
1.160     albertel  816: This is also intended for things like the course initialization helper, where the
1.25      bowersj2  817: user is setting various parameters. By correctly grabbing current settings 
                    818: and including them into the helper, it allows the user to come back to the
                    819: helper later and re-execute it, without needing to worry about overwriting
                    820: some setting accidentally.
                    821: 
                    822: Again, see the course initialization helper for examples.
                    823: 
1.44      bowersj2  824: =head2 validator tagX<validator>
1.38      bowersj2  825: 
                    826: Some elements that accepts user input can contain a "validator" tag that,
                    827: when surrounded by "sub { my $helper = shift; my $state = shift; my $element = shift; my $val = shift " 
                    828: and "}", where "$val" is the value the user entered, will form a subroutine 
                    829: that when called will verify whether the given input is valid or not. If it 
                    830: is valid, the routine will return a false value. If invalid, the routine 
                    831: will return an error message to be displayed for the user.
                    832: 
                    833: Consult the documentation for each element to see whether it supports this 
                    834: tag.
                    835: 
1.44      bowersj2  836: =head2 getValue methodX<getValue (helper elements)>
1.31      bowersj2  837: 
                    838: If the element stores the name of the variable in a 'variable' member, which
                    839: the provided ones all do, you can retreive the value of the variable by calling
                    840: this method.
                    841: 
1.4       bowersj2  842: =cut
                    843: 
1.5       bowersj2  844: BEGIN {
1.7       bowersj2  845:     &Apache::lonhelper::register('Apache::lonhelper::element',
1.25      bowersj2  846:                                  ('nextstate', 'finalcode',
1.38      bowersj2  847:                                   'defaultvalue', 'validator'));
1.5       bowersj2  848: }
                    849: 
1.4       bowersj2  850: # Because we use the param hash, this is often a sufficent
                    851: # constructor
                    852: sub new {
                    853:     my $proto = shift;
                    854:     my $class = ref($proto) || $proto;
                    855:     my $self = $paramHash;
                    856:     bless($self, $class);
                    857: 
                    858:     $self->{PARAMS} = $paramHash;
                    859:     $self->{STATE} = $state;
                    860:     $state->addElement($self);
                    861:     
                    862:     # Ensure param hash is not reused
                    863:     $paramHash = {};
                    864: 
                    865:     return $self;
                    866: }   
                    867: 
1.5       bowersj2  868: sub start_nextstate {
                    869:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    870: 
                    871:     if ($target ne 'helper') {
                    872:         return '';
                    873:     }
                    874:     
                    875:     $paramHash->{NEXTSTATE} = &Apache::lonxml::get_all_text('/nextstate',
                    876:                                                              $parser);
                    877:     return '';
                    878: }
                    879: 
                    880: sub end_nextstate { return ''; }
                    881: 
1.25      bowersj2  882: sub start_finalcode {
                    883:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    884: 
                    885:     if ($target ne 'helper') {
                    886:         return '';
                    887:     }
                    888:     
                    889:     $paramHash->{FINAL_CODE} = &Apache::lonxml::get_all_text('/finalcode',
                    890:                                                              $parser);
                    891:     return '';
                    892: }
                    893: 
                    894: sub end_finalcode { return ''; }
                    895: 
                    896: sub start_defaultvalue {
                    897:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    898: 
                    899:     if ($target ne 'helper') {
                    900:         return '';
                    901:     }
                    902:     
                    903:     $paramHash->{DEFAULT_VALUE} = &Apache::lonxml::get_all_text('/defaultvalue',
                    904:                                                              $parser);
                    905:     $paramHash->{DEFAULT_VALUE} = 'sub { my $helper = shift; my $state = shift;' .
                    906:         $paramHash->{DEFAULT_VALUE} . '}';
                    907:     return '';
                    908: }
                    909: 
                    910: sub end_defaultvalue { return ''; }
                    911: 
1.57      albertel  912: # Validators may need to take language specifications
1.38      bowersj2  913: sub start_validator {
                    914:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    915: 
                    916:     if ($target ne 'helper') {
                    917:         return '';
                    918:     }
                    919:     
                    920:     $paramHash->{VALIDATOR} = &Apache::lonxml::get_all_text('/validator',
                    921:                                                              $parser);
                    922:     $paramHash->{VALIDATOR} = 'sub { my $helper = shift; my $state = shift; my $element = shift; my $val = shift;' .
                    923:         $paramHash->{VALIDATOR} . '}';
                    924:     return '';
                    925: }
                    926: 
                    927: sub end_validator { return ''; }
                    928: 
1.4       bowersj2  929: sub preprocess {
                    930:     return 1;
                    931: }
                    932: 
                    933: sub postprocess {
                    934:     return 1;
                    935: }
                    936: 
                    937: sub render {
                    938:     return '';
                    939: }
                    940: 
1.13      bowersj2  941: sub overrideForm {
                    942:     return 0;
                    943: }
                    944: 
1.31      bowersj2  945: sub getValue {
                    946:     my $self = shift;
                    947:     return $helper->{VARS}->{$self->{'variable'}};
                    948: }
                    949: 
1.4       bowersj2  950: 1;
                    951: 
                    952: package Apache::lonhelper::message;
                    953: 
                    954: =pod
                    955: 
1.48      bowersj2  956: =head1 Elements
                    957: 
                    958: =head2 Element: messageX<message, helper element>
1.4       bowersj2  959: 
1.44      bowersj2  960: Message elements display their contents, and
                    961: transition directly to the state in the <nextstate> attribute. Example:
1.4       bowersj2  962: 
1.44      bowersj2  963:  <message nextstate='GET_NAME'>
                    964:    This is the <b>message</b> the user will see, 
                    965:                  <i>HTML allowed</i>.
1.4       bowersj2  966:    </message>
                    967: 
1.44      bowersj2  968: This will display the HTML message and transition to the 'nextstate' if
1.7       bowersj2  969: given. The HTML will be directly inserted into the helper, so if you don't
1.44      bowersj2  970: want text to run together, you'll need to manually wrap the message text
1.4       bowersj2  971: in <p> tags, or whatever is appropriate for your HTML.
                    972: 
1.5       bowersj2  973: Message tags do not add in whitespace, so if you want it, you'll need to add
                    974: it into states. This is done so you can inline some elements, such as 
                    975: the <date> element, right between two messages, giving the appearence that 
                    976: the <date> element appears inline. (Note the elements can not be embedded
                    977: within each other.)
                    978: 
1.4       bowersj2  979: This is also a good template for creating your own new states, as it has
                    980: very little code beyond the state template.
                    981: 
1.57      albertel  982: =head3 Localization
                    983: 
                    984: The contents of the message tag will be run through the
                    985: normalize_string function and that will be used as a call to &mt.
                    986: 
1.4       bowersj2  987: =cut
                    988: 
                    989: no strict;
                    990: @ISA = ("Apache::lonhelper::element");
                    991: use strict;
1.57      albertel  992: use Apache::lonlocal;
1.4       bowersj2  993: 
                    994: BEGIN {
1.7       bowersj2  995:     &Apache::lonhelper::register('Apache::lonhelper::message',
1.10      bowersj2  996:                               ('message'));
1.3       bowersj2  997: }
                    998: 
1.5       bowersj2  999: sub new {
                   1000:     my $ref = Apache::lonhelper::element->new();
                   1001:     bless($ref);
                   1002: }
1.4       bowersj2 1003: 
                   1004: # CONSTRUCTION: Construct the message element from the XML
                   1005: sub start_message {
                   1006:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1007: 
                   1008:     if ($target ne 'helper') {
                   1009:         return '';
                   1010:     }
1.10      bowersj2 1011: 
1.69      sakharuk 1012:     $paramHash->{MESSAGE_TEXT} = &mtn(&Apache::lonxml::get_all_text('/message',
                   1013:                                                                $parser));
1.10      bowersj2 1014: 
                   1015:     if (defined($token->[2]{'nextstate'})) {
                   1016:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
                   1017:     }
1.162     albertel 1018:     if (defined($token->[2]{'type'})) {
                   1019:         $paramHash->{TYPE} = $token->[2]{'type'};
                   1020:     }
1.4       bowersj2 1021:     return '';
1.3       bowersj2 1022: }
                   1023: 
1.10      bowersj2 1024: sub end_message {
1.4       bowersj2 1025:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1026: 
                   1027:     if ($target ne 'helper') {
                   1028:         return '';
                   1029:     }
1.10      bowersj2 1030:     Apache::lonhelper::message->new();
                   1031:     return '';
1.5       bowersj2 1032: }
                   1033: 
                   1034: sub render {
                   1035:     my $self = shift;
1.162     albertel 1036:     
                   1037:     if ($self->{TYPE} =~ /^\s*warning\s*$/i) {
                   1038: 	 $self->{MESSAGE_TEXT} = 
                   1039: 	     '<span class="LC_warning">'. $self->{MESSAGE_TEXT}.'</span>';
                   1040:     }
                   1041:     if ($self->{TYPE} =~ /^\s*error\s*$/i) {
                   1042: 	 $self->{MESSAGE_TEXT} = 
                   1043: 	     '<span class="LC_error">'. $self->{MESSAGE_TEXT}.'</span>';
                   1044:     }
1.161     albertel 1045:     return $self->{MESSAGE_TEXT};
1.5       bowersj2 1046: }
                   1047: # If a NEXTSTATE was given, switch to it
                   1048: sub postprocess {
                   1049:     my $self = shift;
                   1050:     if (defined($self->{NEXTSTATE})) {
                   1051:         $helper->changeState($self->{NEXTSTATE});
                   1052:     }
1.6       bowersj2 1053: 
                   1054:     return 1;
1.5       bowersj2 1055: }
                   1056: 1;
                   1057: 
1.159     albertel 1058: package Apache::lonhelper::helpicon;
                   1059: 
                   1060: =pod
                   1061: 
                   1062: =head1 Elements
                   1063: 
                   1064: =head2 Element: helpiconX<helpicon, helper element>
                   1065: 
                   1066: Helpicon elements add a help icon at the current location.
                   1067: Example:
                   1068: 
                   1069:    <helpicon file="Help">
                   1070:      General Help
                   1071:    </helpicon>
                   1072: 
                   1073: In this example will generate a help icon to the Help.hlp url with a
                   1074: description of 'General Help'. The description is not required and if
                   1075: left out (Example: <helpicon file="Help" /> only the icon will be
                   1076: added.)
                   1077: 
                   1078: =head3 Localization
                   1079: 
                   1080: The description text will be run through the normalize_string function
                   1081: and that will be used as a call to &mt.
                   1082: 
                   1083: =cut
                   1084: 
                   1085: no strict;
                   1086: @ISA = ("Apache::lonhelper::element");
                   1087: use strict;
                   1088: use Apache::lonlocal;
                   1089: 
                   1090: BEGIN {
                   1091:     &Apache::lonhelper::register('Apache::lonhelper::helpicon',
                   1092: 				 ('helpicon'));
                   1093: }
                   1094: 
                   1095: sub new {
                   1096:     my $ref = Apache::lonhelper::element->new();
                   1097:     bless($ref);
                   1098: }
                   1099: 
                   1100: # CONSTRUCTION: Construct the message element from the XML
                   1101: sub start_helpicon {
                   1102:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1103: 
                   1104:     if ($target ne 'helper') {
                   1105:         return '';
                   1106:     }
                   1107: 
                   1108:     $paramHash->{HELP_TEXT} = &mtn(&Apache::lonxml::get_all_text('/helpicon',
                   1109: 								 $parser));
                   1110: 
                   1111:     $paramHash->{HELP_TEXT} =~s/^\s+//;
                   1112:     $paramHash->{HELP_TEXT} =~s/\s+$//;
                   1113: 
                   1114:     if (defined($token->[2]{'file'})) {
                   1115:         $paramHash->{HELP_FILE} = $token->[2]{'file'};
                   1116:     }
                   1117:     return '';
                   1118: }
                   1119: 
                   1120: sub end_helpicon {
                   1121:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1122: 
                   1123:     if ($target ne 'helper') {
                   1124:         return '';
                   1125:     }
                   1126:     Apache::lonhelper::helpicon->new();
                   1127:     return '';
                   1128: }
                   1129: 
                   1130: sub render {
                   1131:     my $self = shift;
                   1132: 
                   1133:     my $text;
                   1134:     if ( $self->{HELP_TEXT} ne '') {
1.160     albertel 1135: 	$text=&mtn($self->{HELP_TEXT});
1.159     albertel 1136:     }
                   1137: 
                   1138:     return &Apache::loncommon::help_open_topic($self->{HELP_FILE},
                   1139: 					       $text);
                   1140: }
1.160     albertel 1141: sub postprocess {
                   1142:     my $self = shift;
                   1143:     if (defined($self->{NEXTSTATE})) {
                   1144:         $helper->changeState($self->{NEXTSTATE});
                   1145:     }
                   1146: 
                   1147:     return 1;
                   1148: }
                   1149: 
1.159     albertel 1150: 1;
                   1151: 
1.155     albertel 1152: package Apache::lonhelper::skip;
                   1153: 
                   1154: =pod
                   1155: 
                   1156: =head1 Elements
                   1157: 
                   1158: =head2 Element: skipX<skip>
                   1159: 
                   1160: The <skip> tag allows you define conditions under which the current state 
                   1161: should be skipped over and define what state to skip to.
                   1162: 
                   1163:   <state name="SKIP">
                   1164:     <skip>
                   1165:        <clause>
                   1166:          #some code that decides whether to skip the state or not
                   1167:        </clause>
                   1168:        <nextstate>FINISH</nextstate>
                   1169:     </skip>
                   1170:     <message nextstate="FINISH">A possibly skipped state</message>
                   1171:   </state>
                   1172: 
                   1173: =cut
                   1174: 
                   1175: no strict;
                   1176: @ISA = ("Apache::lonhelper::element");
                   1177: use strict;
                   1178: 
                   1179: BEGIN {
                   1180:     &Apache::lonhelper::register('Apache::lonhelper::skip',
                   1181: 				 ('skip'));
                   1182: }
                   1183: 
                   1184: sub new {
                   1185:     my $ref = Apache::lonhelper::element->new();
                   1186:     bless($ref);
                   1187: }
                   1188: 
                   1189: sub start_skip {
                   1190:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1191: 
                   1192:     if ($target ne 'helper') {
                   1193:         return '';
                   1194:     }
                   1195:     # let <cluase> know what text to skip to
                   1196:     $paramHash->{SKIPTAG}='/skip';
                   1197:     return '';
                   1198: }
                   1199: 
                   1200: sub end_skip {
                   1201:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1202: 
                   1203:     if ($target ne 'helper') {
                   1204:         return '';
                   1205:     }
                   1206:     Apache::lonhelper::skip->new();
                   1207:     return '';
                   1208: }
                   1209: 
                   1210: sub render {
                   1211:     my $self = shift;
                   1212:     return '';
                   1213: }
                   1214: # If a NEXTSTATE is set, switch to it
                   1215: sub preprocess {
                   1216:     my ($self) = @_;
                   1217: 
                   1218:     if (defined($self->{NEXTSTATE})) {
                   1219:         $helper->changeState($self->{NEXTSTATE});
                   1220:     }
                   1221: 
                   1222:     return 1;
                   1223: }
                   1224: 
                   1225: 1;
                   1226: 
1.5       bowersj2 1227: package Apache::lonhelper::choices;
                   1228: 
                   1229: =pod
                   1230: 
1.44      bowersj2 1231: =head2 Element: choicesX<choices, helper element>
1.5       bowersj2 1232: 
                   1233: Choice states provide a single choice to the user as a text selection box.
                   1234: A "choice" is two pieces of text, one which will be displayed to the user
                   1235: (the "human" value), and one which will be passed back to the program
                   1236: (the "computer" value). For instance, a human may choose from a list of
                   1237: resources on disk by title, while your program wants the file name.
                   1238: 
                   1239: <choices> takes an attribute "variable" to control which helper variable
                   1240: the result is stored in.
                   1241: 
                   1242: <choices> takes an attribute "multichoice" which, if set to a true
                   1243: value, will allow the user to select multiple choices.
                   1244: 
1.26      bowersj2 1245: <choices> takes an attribute "allowempty" which, if set to a true 
                   1246: value, will allow the user to select none of the choices without raising
                   1247: an error message.
                   1248: 
1.44      bowersj2 1249: =head3 SUB-TAGS
1.5       bowersj2 1250: 
1.44      bowersj2 1251: <choices> can have the following subtags:X<choice, helper tag>
1.5       bowersj2 1252: 
                   1253: =over 4
                   1254: 
                   1255: =item * <nextstate>state_name</nextstate>: If given, this will cause the
1.44      bowersj2 1256:       choice element to transition to the given state after executing.
                   1257:       This will override the <nextstate> passed to <choices> (if any).
1.5       bowersj2 1258: 
                   1259: =item * <choice />: If the choices are static,
                   1260:       this element will allow you to specify them. Each choice
                   1261:       contains  attribute, "computer", as described above. The
                   1262:       content of the tag will be used as the human label.
                   1263:       For example,  
                   1264:       <choice computer='234-12-7312'>Bobby McDormik</choice>.
                   1265: 
1.44      bowersj2 1266: <choice> can take a parameter "eval", which if set to
                   1267: a true value, will cause the contents of the tag to be
                   1268: evaluated as it would be in an <eval> tag; see <eval> tag
                   1269: below.
1.13      bowersj2 1270: 
1.5       bowersj2 1271: <choice> may optionally contain a 'nextstate' attribute, which
1.44      bowersj2 1272: will be the state transistioned to if the choice is made, if
                   1273: the choice is not multichoice. This will override the nextstate
                   1274: passed to the parent C<choices> tag.
1.5       bowersj2 1275: 
1.136     foxr     1276: <choice> may optionally contain a 'relatedvalue' attribute, which
                   1277: if present will cause a text entry to appear to the right of the
                   1278: selection.  The value of the relatedvalue attribute is a variable
                   1279: into which the text entry will be stored e.g.:
                   1280: <choice computer='numberprovided" relatedvalue="num">Type the number in:</choice>
                   1281: 
                   1282: <choice> may contain a relatededefault atribute which, if the
                   1283: relatedvalue attribute is present will be the initial value of the input
                   1284: box.
                   1285: 
1.5       bowersj2 1286: =back
                   1287: 
                   1288: To create the choices programmatically, either wrap the choices in 
                   1289: <condition> tags (prefered), or use an <exec> block inside the <choice>
                   1290: tag. Store the choices in $state->{CHOICES}, which is a list of list
                   1291: references, where each list has three strings. The first is the human
                   1292: name, the second is the computer name. and the third is the option
                   1293: next state. For example:
                   1294: 
                   1295:  <exec>
                   1296:     for (my $i = 65; $i < 65 + 26; $i++) {
                   1297:         push @{$state->{CHOICES}}, [chr($i), $i, 'next'];
                   1298:     }
                   1299:  </exec>
                   1300: 
                   1301: This will allow the user to select from the letters A-Z (in ASCII), while
                   1302: passing the ASCII value back into the helper variables, and the state
                   1303: will in all cases transition to 'next'.
                   1304: 
                   1305: You can mix and match methods of creating choices, as long as you always 
                   1306: "push" onto the choice list, rather then wiping it out. (You can even 
                   1307: remove choices programmatically, but that would probably be bad form.)
                   1308: 
1.44      bowersj2 1309: =head3 defaultvalue support
1.25      bowersj2 1310: 
                   1311: Choices supports default values both in multichoice and single choice mode.
                   1312: In single choice mode, have the defaultvalue tag's function return the 
                   1313: computer value of the box you want checked. If the function returns a value
                   1314: that does not correspond to any of the choices, the default behavior of selecting
                   1315: the first choice will be preserved.
                   1316: 
                   1317: For multichoice, return a string with the computer values you want checked,
                   1318: delimited by triple pipes. Note this matches how the result of the <choices>
                   1319: tag is stored in the {VARS} hash.
                   1320: 
1.5       bowersj2 1321: =cut
                   1322: 
                   1323: no strict;
                   1324: @ISA = ("Apache::lonhelper::element");
                   1325: use strict;
1.57      albertel 1326: use Apache::lonlocal;
1.100     albertel 1327: use Apache::lonnet;
1.5       bowersj2 1328: 
                   1329: BEGIN {
1.7       bowersj2 1330:     &Apache::lonhelper::register('Apache::lonhelper::choices',
1.5       bowersj2 1331:                               ('choice', 'choices'));
                   1332: }
                   1333: 
                   1334: sub new {
                   1335:     my $ref = Apache::lonhelper::element->new();
                   1336:     bless($ref);
                   1337: }
                   1338: 
                   1339: # CONSTRUCTION: Construct the message element from the XML
                   1340: sub start_choices {
                   1341:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1342: 
                   1343:     if ($target ne 'helper') {
                   1344:         return '';
                   1345:     }
                   1346: 
                   1347:     # Need to initialize the choices list, so everything can assume it exists
1.24      sakharuk 1348:     $paramHash->{'variable'} = $token->[2]{'variable'} if (!defined($paramHash->{'variable'}));
1.5       bowersj2 1349:     $helper->declareVar($paramHash->{'variable'});
                   1350:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.26      bowersj2 1351:     $paramHash->{'allowempty'} = $token->[2]{'allowempty'};
1.5       bowersj2 1352:     $paramHash->{CHOICES} = [];
                   1353:     return '';
                   1354: }
                   1355: 
                   1356: sub end_choices {
                   1357:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1358: 
                   1359:     if ($target ne 'helper') {
                   1360:         return '';
                   1361:     }
                   1362:     Apache::lonhelper::choices->new();
                   1363:     return '';
                   1364: }
                   1365: 
                   1366: sub start_choice {
                   1367:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1368: 
                   1369:     if ($target ne 'helper') {
                   1370:         return '';
                   1371:     }
                   1372: 
                   1373:     my $computer = $token->[2]{'computer'};
1.69      sakharuk 1374:     my $human = &mt(&Apache::lonxml::get_all_text('/choice',
                   1375:                                               $parser));
1.136     foxr     1376:     my $nextstate  = $token->[2]{'nextstate'};
                   1377:     my $evalFlag   = $token->[2]{'eval'};
                   1378:     my $relatedVar = $token->[2]{'relatedvalue'}; 
                   1379:     my $relatedDefault = $token->[2]{'relateddefault'};
1.94      albertel 1380:     push @{$paramHash->{CHOICES}}, [&mtn($human), $computer, $nextstate, 
1.136     foxr     1381:                                     $evalFlag, $relatedVar, $relatedDefault];
1.5       bowersj2 1382:     return '';
                   1383: }
                   1384: 
                   1385: sub end_choice {
                   1386:     return '';
                   1387: }
                   1388: 
1.87      matthew  1389: {
                   1390:     # used to generate unique id attributes for <input> tags. 
                   1391:     # internal use only.
                   1392:     my $id = 0;
                   1393:     sub new_id { return $id++; }
                   1394: }
                   1395: 
1.5       bowersj2 1396: sub render {
                   1397:     my $self = shift;
                   1398:     my $var = $self->{'variable'};
                   1399:     my $buttons = '';
                   1400:     my $result = '';
                   1401: 
                   1402:     if ($self->{'multichoice'}) {
1.6       bowersj2 1403:         $result .= <<SCRIPT;
1.112     albertel 1404: <script type="text/javascript">
                   1405: // <!--
1.18      bowersj2 1406:     function checkall(value, checkName) {
1.15      bowersj2 1407: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
1.18      bowersj2 1408:             ele = document.forms.helpform.elements[i];
1.157     raeburn  1409:             if (ele.name == checkName + '_forminput') {
1.18      bowersj2 1410:                 document.forms.helpform.elements[i].checked=value;
                   1411:             }
1.5       bowersj2 1412:         }
                   1413:     }
1.112     albertel 1414: // -->
1.5       bowersj2 1415: </script>
                   1416: SCRIPT
1.25      bowersj2 1417:     }
                   1418: 
                   1419:     # Only print "select all" and "unselect all" if there are five or
                   1420:     # more choices; fewer then that and it looks silly.
                   1421:     if ($self->{'multichoice'} && scalar(@{$self->{CHOICES}}) > 4) {
1.68      sakharuk 1422:         my %lt=&Apache::lonlocal::texthash(
                   1423: 			'sa'  => "Select All",
                   1424: 		        'ua'  => "Unselect All");
1.5       bowersj2 1425:         $buttons = <<BUTTONS;
                   1426: <br />
1.68      sakharuk 1427: <input type="button" onclick="checkall(true, '$var')" value="$lt{'sa'}" />
                   1428: <input type="button" onclick="checkall(false, '$var')" value="$lt{'ua'}" />
1.6       bowersj2 1429: <br />&nbsp;
1.5       bowersj2 1430: BUTTONS
                   1431:     }
                   1432: 
1.16      bowersj2 1433:     if (defined $self->{ERROR_MSG}) {
1.6       bowersj2 1434:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br />';
1.5       bowersj2 1435:     }
                   1436: 
                   1437:     $result .= $buttons;
1.6       bowersj2 1438:     
1.5       bowersj2 1439:     $result .= "<table>\n\n";
                   1440: 
1.25      bowersj2 1441:     my %checkedChoices;
                   1442:     my $checkedChoicesFunc;
                   1443: 
                   1444:     if (defined($self->{DEFAULT_VALUE})) {
                   1445:         $checkedChoicesFunc = eval ($self->{DEFAULT_VALUE});
                   1446:         die 'Error in default value code for variable ' . 
1.34      bowersj2 1447:             $self->{'variable'} . ', Perl said: ' . $@ if $@;
1.25      bowersj2 1448:     } else {
                   1449:         $checkedChoicesFunc = sub { return ''; };
                   1450:     }
                   1451: 
                   1452:     # Process which choices should be checked.
                   1453:     if ($self->{'multichoice'}) {
                   1454:         for my $selectedChoice (split(/\|\|\|/, (&$checkedChoicesFunc($helper, $self)))) {
                   1455:             $checkedChoices{$selectedChoice} = 1;
                   1456:         }
                   1457:     } else {
                   1458:         # single choice
                   1459:         my $selectedChoice = &$checkedChoicesFunc($helper, $self);
                   1460:         
                   1461:         my $foundChoice = 0;
                   1462:         
                   1463:         # check that the choice is in the list of choices.
                   1464:         for my $choice (@{$self->{CHOICES}}) {
                   1465:             if ($choice->[1] eq $selectedChoice) {
                   1466:                 $checkedChoices{$choice->[1]} = 1;
                   1467:                 $foundChoice = 1;
                   1468:             }
                   1469:         }
                   1470:         
                   1471:         # If we couldn't find the choice, pick the first one 
                   1472:         if (!$foundChoice) {
                   1473:             $checkedChoices{$self->{CHOICES}->[0]->[1]} = 1;
                   1474:         }
                   1475:     }
                   1476: 
1.5       bowersj2 1477:     my $type = "radio";
                   1478:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
                   1479:     foreach my $choice (@{$self->{CHOICES}}) {
1.87      matthew  1480:         my $id = &new_id();
1.5       bowersj2 1481:         $result .= "<tr>\n<td width='20'>&nbsp;</td>\n";
1.157     raeburn  1482:         $result .= "<td valign='top'><input type='$type' name='${var}_forminput'"
1.111     albertel 1483:             . " value='" . 
1.89      foxr     1484:             HTML::Entities::encode($choice->[1],"<>&\"'") 
1.5       bowersj2 1485:             . "'";
1.25      bowersj2 1486:         if ($checkedChoices{$choice->[1]}) {
1.182     raeburn  1487:             $result .= " checked='checked'";
1.5       bowersj2 1488:         }
1.182     raeburn  1489:         $result .= qq{ id="id$id"};
1.13      bowersj2 1490:         my $choiceLabel = $choice->[0];
1.136     foxr     1491:         if ($choice->[3]) {  # if we need to evaluate this choice
1.13      bowersj2 1492:             $choiceLabel = "sub { my $helper = shift; my $state = shift;" .
                   1493:                 $choiceLabel . "}";
                   1494:             $choiceLabel = eval($choiceLabel);
                   1495:             $choiceLabel = &$choiceLabel($helper, $self);
                   1496:         }
1.182     raeburn  1497:         $result .= " /></td><td> ".qq{<label for="id$id">}.
1.164     albertel 1498: 	    $choiceLabel. "</label></td>";
1.136     foxr     1499: 	if ($choice->[4]) {
                   1500: 	    $result .='<td><input type="text" size="5" name="'
1.157     raeburn  1501: 		.$choice->[4].'_forminput" value="'
1.136     foxr     1502:                 .$choice->[5].'" /></td>';
                   1503: 	}
                   1504: 	$result .= "</tr>\n";
1.5       bowersj2 1505:     }
                   1506:     $result .= "</table>\n\n\n";
                   1507:     $result .= $buttons;
                   1508: 
                   1509:     return $result;
                   1510: }
                   1511: 
                   1512: # If a NEXTSTATE was given or a nextstate for this choice was
                   1513: # given, switch to it
                   1514: sub postprocess {
                   1515:     my $self = shift;
1.157     raeburn  1516:     my $chosenValue = $env{'form.' . $self->{'variable'} . '_forminput'};
1.5       bowersj2 1517: 
1.171     foxr     1518: 
1.26      bowersj2 1519:     if (!defined($chosenValue) && !$self->{'allowempty'}) {
1.59      bowersj2 1520:         $self->{ERROR_MSG} = 
                   1521: 	    &mt("You must choose one or more choices to continue.");
1.6       bowersj2 1522:         return 0;
                   1523:     }
                   1524: 
1.171     foxr     1525: 
                   1526: 
1.28      bowersj2 1527:     if (ref($chosenValue)) {
                   1528:         $helper->{VARS}->{$self->{'variable'}} = join('|||', @$chosenValue);
1.42      bowersj2 1529:     }
                   1530: 
                   1531:     if (defined($self->{NEXTSTATE})) {
                   1532:         $helper->changeState($self->{NEXTSTATE});
                   1533:     }
                   1534:     
                   1535:     foreach my $choice (@{$self->{CHOICES}}) {
                   1536:         if ($choice->[1] eq $chosenValue) {
                   1537:             if (defined($choice->[2])) {
                   1538:                 $helper->changeState($choice->[2]);
                   1539:             }
                   1540:         }
1.136     foxr     1541: 	if ($choice->[4]) {
                   1542: 	    my $varname = $choice->[4];
1.157     raeburn  1543: 	    $helper->{'VARS'}->{$varname} = $env{'form.'."${varname}_forminput"};
1.136     foxr     1544: 	}
1.42      bowersj2 1545:     }
                   1546:     return 1;
                   1547: }
                   1548: 1;
                   1549: 
                   1550: package Apache::lonhelper::dropdown;
                   1551: 
                   1552: =pod
                   1553: 
1.44      bowersj2 1554: =head2 Element: dropdownX<dropdown, helper tag>
1.42      bowersj2 1555: 
                   1556: A drop-down provides a drop-down box instead of a radio button
                   1557: box. Because most people do not know how to use a multi-select
                   1558: drop-down box, that option is not allowed. Otherwise, the arguments
                   1559: are the same as "choices", except "allowempty" is also meaningless.
                   1560: 
                   1561: <dropdown> takes an attribute "variable" to control which helper variable
                   1562: the result is stored in.
                   1563: 
1.44      bowersj2 1564: =head3 SUB-TAGS
1.42      bowersj2 1565: 
                   1566: <choice>, which acts just as it does in the "choices" element.
                   1567: 
                   1568: =cut
                   1569: 
1.57      albertel 1570: # This really ought to be a sibling class to "choice" which is itself
                   1571: # a child of some abstract class.... *shrug*
                   1572: 
1.42      bowersj2 1573: no strict;
                   1574: @ISA = ("Apache::lonhelper::element");
                   1575: use strict;
1.57      albertel 1576: use Apache::lonlocal;
1.100     albertel 1577: use Apache::lonnet;
1.42      bowersj2 1578: 
                   1579: BEGIN {
                   1580:     &Apache::lonhelper::register('Apache::lonhelper::dropdown',
                   1581:                               ('dropdown'));
                   1582: }
                   1583: 
                   1584: sub new {
                   1585:     my $ref = Apache::lonhelper::element->new();
                   1586:     bless($ref);
                   1587: }
                   1588: 
                   1589: # CONSTRUCTION: Construct the message element from the XML
                   1590: sub start_dropdown {
                   1591:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1592: 
                   1593:     if ($target ne 'helper') {
                   1594:         return '';
                   1595:     }
                   1596: 
                   1597:     # Need to initialize the choices list, so everything can assume it exists
                   1598:     $paramHash->{'variable'} = $token->[2]{'variable'} if (!defined($paramHash->{'variable'}));
                   1599:     $helper->declareVar($paramHash->{'variable'});
                   1600:     $paramHash->{CHOICES} = [];
                   1601:     return '';
                   1602: }
                   1603: 
                   1604: sub end_dropdown {
                   1605:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1606: 
                   1607:     if ($target ne 'helper') {
                   1608:         return '';
                   1609:     }
                   1610:     Apache::lonhelper::dropdown->new();
                   1611:     return '';
                   1612: }
                   1613: 
                   1614: sub render {
                   1615:     my $self = shift;
                   1616:     my $var = $self->{'variable'};
                   1617:     my $result = '';
                   1618: 
                   1619:     if (defined $self->{ERROR_MSG}) {
                   1620:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br />';
                   1621:     }
                   1622: 
                   1623:     my %checkedChoices;
                   1624:     my $checkedChoicesFunc;
                   1625: 
                   1626:     if (defined($self->{DEFAULT_VALUE})) {
                   1627:         $checkedChoicesFunc = eval ($self->{DEFAULT_VALUE});
                   1628:         die 'Error in default value code for variable ' . 
                   1629:             $self->{'variable'} . ', Perl said: ' . $@ if $@;
                   1630:     } else {
                   1631:         $checkedChoicesFunc = sub { return ''; };
                   1632:     }
                   1633: 
                   1634:     # single choice
                   1635:     my $selectedChoice = &$checkedChoicesFunc($helper, $self);
                   1636:     
                   1637:     my $foundChoice = 0;
                   1638:     
                   1639:     # check that the choice is in the list of choices.
                   1640:     for my $choice (@{$self->{CHOICES}}) {
                   1641: 	if ($choice->[1] eq $selectedChoice) {
                   1642: 	    $checkedChoices{$choice->[1]} = 1;
                   1643: 	    $foundChoice = 1;
                   1644: 	}
                   1645:     }
                   1646:     
                   1647:     # If we couldn't find the choice, pick the first one 
                   1648:     if (!$foundChoice) {
                   1649: 	$checkedChoices{$self->{CHOICES}->[0]->[1]} = 1;
                   1650:     }
                   1651: 
1.157     raeburn  1652:     $result .= "<select name='${var}_forminput'>\n";
1.42      bowersj2 1653:     foreach my $choice (@{$self->{CHOICES}}) {
                   1654:         $result .= "<option value='" . 
1.89      foxr     1655:             HTML::Entities::encode($choice->[1],"<>&\"'") 
1.42      bowersj2 1656:             . "'";
                   1657:         if ($checkedChoices{$choice->[1]}) {
1.111     albertel 1658:             $result .= " selected='selected' ";
1.42      bowersj2 1659:         }
                   1660:         my $choiceLabel = $choice->[0];
                   1661:         if ($choice->[4]) {  # if we need to evaluate this choice
                   1662:             $choiceLabel = "sub { my $helper = shift; my $state = shift;" .
                   1663:                 $choiceLabel . "}";
                   1664:             $choiceLabel = eval($choiceLabel);
                   1665:             $choiceLabel = &$choiceLabel($helper, $self);
                   1666:         }
1.112     albertel 1667:         $result .= ">" . &mtn($choiceLabel) . "</option>\n";
1.42      bowersj2 1668:     }
1.43      bowersj2 1669:     $result .= "</select>\n";
1.42      bowersj2 1670: 
                   1671:     return $result;
                   1672: }
                   1673: 
                   1674: # If a NEXTSTATE was given or a nextstate for this choice was
                   1675: # given, switch to it
                   1676: sub postprocess {
                   1677:     my $self = shift;
1.157     raeburn  1678:     my $chosenValue = $env{'form.' . $self->{'variable'} . '_forminput'};
1.42      bowersj2 1679: 
                   1680:     if (!defined($chosenValue) && !$self->{'allowempty'}) {
                   1681:         $self->{ERROR_MSG} = "You must choose one or more choices to" .
                   1682:             " continue.";
                   1683:         return 0;
1.6       bowersj2 1684:     }
                   1685: 
1.5       bowersj2 1686:     if (defined($self->{NEXTSTATE})) {
                   1687:         $helper->changeState($self->{NEXTSTATE});
                   1688:     }
                   1689:     
                   1690:     foreach my $choice (@{$self->{CHOICES}}) {
                   1691:         if ($choice->[1] eq $chosenValue) {
                   1692:             if (defined($choice->[2])) {
                   1693:                 $helper->changeState($choice->[2]);
                   1694:             }
                   1695:         }
                   1696:     }
1.6       bowersj2 1697:     return 1;
1.5       bowersj2 1698: }
                   1699: 1;
                   1700: 
                   1701: package Apache::lonhelper::date;
                   1702: 
                   1703: =pod
                   1704: 
1.44      bowersj2 1705: =head2 Element: dateX<date, helper element>
1.5       bowersj2 1706: 
                   1707: Date elements allow the selection of a date with a drop down list.
                   1708: 
                   1709: Date elements can take two attributes:
                   1710: 
                   1711: =over 4
                   1712: 
                   1713: =item * B<variable>: The name of the variable to store the chosen
                   1714:         date in. Required.
                   1715: 
                   1716: =item * B<hoursminutes>: If a true value, the date will show hours
                   1717:         and minutes, as well as month/day/year. If false or missing,
                   1718:         the date will only show the month, day, and year.
                   1719: 
                   1720: =back
                   1721: 
                   1722: Date elements contain only an option <nextstate> tag to determine
                   1723: the next state.
                   1724: 
                   1725: Example:
                   1726: 
                   1727:  <date variable="DUE_DATE" hoursminutes="1">
                   1728:    <nextstate>choose_why</nextstate>
                   1729:    </date>
                   1730: 
                   1731: =cut
                   1732: 
                   1733: no strict;
                   1734: @ISA = ("Apache::lonhelper::element");
                   1735: use strict;
1.57      albertel 1736: use Apache::lonlocal; # A localization nightmare
1.100     albertel 1737: use Apache::lonnet;
1.166     raeburn  1738: use DateTime;
1.5       bowersj2 1739: 
                   1740: BEGIN {
1.7       bowersj2 1741:     &Apache::lonhelper::register('Apache::lonhelper::date',
1.5       bowersj2 1742:                               ('date'));
                   1743: }
                   1744: 
                   1745: # Don't need to override the "new" from element
                   1746: sub new {
                   1747:     my $ref = Apache::lonhelper::element->new();
                   1748:     bless($ref);
                   1749: }
                   1750: 
                   1751: my @months = ("January", "February", "March", "April", "May", "June", "July",
                   1752: 	      "August", "September", "October", "November", "December");
                   1753: 
                   1754: # CONSTRUCTION: Construct the message element from the XML
                   1755: sub start_date {
                   1756:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1757: 
                   1758:     if ($target ne 'helper') {
                   1759:         return '';
                   1760:     }
                   1761: 
                   1762:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   1763:     $helper->declareVar($paramHash->{'variable'});
                   1764:     $paramHash->{'hoursminutes'} = $token->[2]{'hoursminutes'};
1.118     albertel 1765:     $paramHash->{'anytime'} = $token->[2]{'anytime'};
1.5       bowersj2 1766: }
                   1767: 
                   1768: sub end_date {
                   1769:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1770: 
                   1771:     if ($target ne 'helper') {
                   1772:         return '';
                   1773:     }
                   1774:     Apache::lonhelper::date->new();
                   1775:     return '';
                   1776: }
                   1777: 
                   1778: sub render {
                   1779:     my $self = shift;
                   1780:     my $result = "";
                   1781:     my $var = $self->{'variable'};
                   1782: 
                   1783:     my $date;
1.118     albertel 1784: 
                   1785:     my $time=time;
1.119     albertel 1786:     my ($anytime,$onclick);
1.118     albertel 1787: 
1.137     albertel 1788:     # first check VARS for a valid new value from the user
                   1789:     # then check DEFAULT_VALUE for a valid default time value
                   1790:     # otherwise pick now as reasonably good time
                   1791: 
                   1792:     if (defined($helper->{VARS}{$var})
                   1793: 	&&  $helper->{VARS}{$var} > 0) {
1.166     raeburn  1794:         $date = &get_date_object($helper->{VARS}{$var}); 
1.137     albertel 1795:     } elsif (defined($self->{DEFAULT_VALUE})) {
1.118     albertel 1796:         my $valueFunc = eval($self->{DEFAULT_VALUE});
                   1797:         die('Error in default value code for variable ' . 
                   1798:             $self->{'variable'} . ', Perl said: ' . $@) if $@;
                   1799:         $time = &$valueFunc($helper, $self);
1.130     albertel 1800: 	if (lc($time) eq 'anytime') {
                   1801: 	    $anytime=1;
1.166     raeburn  1802: 	    $date = &get_date_object(time);
1.137     albertel 1803: 	    $date->min(0);
                   1804: 	} elsif (defined($time) && $time ne 0) {
1.166     raeburn  1805: 	    $date = &get_date_object($time);
1.130     albertel 1806: 	} else {
1.137     albertel 1807: 	    # leave date undefined so it'll default to now
1.130     albertel 1808: 	}
1.137     albertel 1809:     }
1.130     albertel 1810: 
1.138     albertel 1811:     if (!defined($date)) {
1.166     raeburn  1812: 	$date = &get_date_object(time);
1.137     albertel 1813: 	$date->min(0);
1.118     albertel 1814:     }
1.137     albertel 1815: 
1.119     albertel 1816:     if ($anytime) {
                   1817: 	$onclick = "onclick=\"javascript:updateCheck(this.form,'${var}anytime',false)\"";
                   1818:     }
1.5       bowersj2 1819:     # Default date: The current hour.
                   1820: 
                   1821:     if (defined $self->{ERROR_MSG}) {
                   1822:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   1823:     }
                   1824: 
                   1825:     # Month
                   1826:     my $i;
1.119     albertel 1827:     $result .= "<select $onclick name='${var}month'>\n";
1.5       bowersj2 1828:     for ($i = 0; $i < 12; $i++) {
1.166     raeburn  1829:         if (($i + 1) == $date->mon) {
1.111     albertel 1830:             $result .= "<option value='$i' selected='selected'>";
1.5       bowersj2 1831:         } else {
                   1832:             $result .= "<option value='$i'>";
                   1833:         }
1.166     raeburn  1834:         $result .= &mt($months[$i])."</option>\n";
1.5       bowersj2 1835:     }
                   1836:     $result .= "</select>\n";
                   1837: 
                   1838:     # Day
1.119     albertel 1839:     $result .= "<select $onclick name='${var}day'>\n";
1.5       bowersj2 1840:     for ($i = 1; $i < 32; $i++) {
                   1841:         if ($i == $date->mday) {
1.111     albertel 1842:             $result .= '<option selected="selected">';
1.5       bowersj2 1843:         } else {
                   1844:             $result .= '<option>';
                   1845:         }
                   1846:         $result .= "$i</option>\n";
                   1847:     }
                   1848:     $result .= "</select>,\n";
                   1849: 
                   1850:     # Year
1.119     albertel 1851:     $result .= "<select $onclick name='${var}year'>\n";
1.5       bowersj2 1852:     for ($i = 2000; $i < 2030; $i++) { # update this after 64-bit dates
1.166     raeburn  1853:         if ($date->year == $i) {
1.111     albertel 1854:             $result .= "<option selected='selected'>";
1.5       bowersj2 1855:         } else {
                   1856:             $result .= "<option>";
                   1857:         }
                   1858:         $result .= "$i</option>\n";
                   1859:     }
                   1860:     $result .= "</select>,\n";
                   1861: 
                   1862:     # Display Hours and Minutes if they are called for
                   1863:     if ($self->{'hoursminutes'}) {
1.59      bowersj2 1864: 	# This needs parameterization for times.
                   1865: 	my $am = &mt('a.m.');
                   1866: 	my $pm = &mt('p.m.');
1.5       bowersj2 1867:         # Build hour
1.119     albertel 1868:         $result .= "<select $onclick name='${var}hour'>\n";
1.111     albertel 1869:         $result .= "<option " . ($date->hour == 0 ? 'selected="selected" ':'') .
1.59      bowersj2 1870:             " value='0'>" . &mt('midnight') . "</option>\n";
1.5       bowersj2 1871:         for ($i = 1; $i < 12; $i++) {
                   1872:             if ($date->hour == $i) {
1.111     albertel 1873:                 $result .= "<option selected='selected' value='$i'>$i $am</option>\n";
1.5       bowersj2 1874:             } else {
1.59      bowersj2 1875:                 $result .= "<option value='$i'>$i $am</option>\n";
1.5       bowersj2 1876:             }
                   1877:         }
1.111     albertel 1878:         $result .= "<option " . ($date->hour == 12 ? 'selected="selected" ':'') .
1.59      bowersj2 1879:             " value='12'>" . &mt('noon') . "</option>\n";
1.5       bowersj2 1880:         for ($i = 13; $i < 24; $i++) {
                   1881:             my $printedHour = $i - 12;
                   1882:             if ($date->hour == $i) {
1.111     albertel 1883:                 $result .= "<option selected='selected' value='$i'>$printedHour $pm</option>\n";
1.5       bowersj2 1884:             } else {
1.59      bowersj2 1885:                 $result .= "<option value='$i'>$printedHour $pm</option>\n";
1.5       bowersj2 1886:             }
                   1887:         }
                   1888: 
                   1889:         $result .= "</select> :\n";
                   1890: 
1.119     albertel 1891:         $result .= "<select $onclick name='${var}minute'>\n";
1.120     albertel 1892: 	my $selected=0;
                   1893:         for my $i ((0,15,30,45,59,undef,0..59)) {
1.5       bowersj2 1894:             my $printedMinute = $i;
1.117     albertel 1895:             if (defined($i) && $i < 10) {
1.5       bowersj2 1896:                 $printedMinute = "0" . $printedMinute;
                   1897:             }
1.120     albertel 1898:             if (!$selected && $date->min == $i) {
1.111     albertel 1899:                 $result .= "<option selected='selected'>";
1.120     albertel 1900: 		$selected=1;
1.5       bowersj2 1901:             } else {
                   1902:                 $result .= "<option>";
                   1903:             }
                   1904:             $result .= "$printedMinute</option>\n";
                   1905:         }
                   1906:         $result .= "</select>\n";
                   1907:     }
1.166     raeburn  1908:     $result  .= ' '.$date->time_zone_short_name().' ';
1.118     albertel 1909:     if ($self->{'anytime'}) {
1.121     albertel 1910: 	$result.=(<<CHECK);
1.119     albertel 1911: <script type="text/javascript">
                   1912: // <!--
                   1913:     function updateCheck(form,name,value) {
                   1914: 	var checkbox=form[name];
                   1915: 	checkbox.checked = value;
                   1916:     }
                   1917: // -->
                   1918: </script>
                   1919: CHECK
1.118     albertel 1920: 	$result.="&nbsp;or&nbsp;<label><input type='checkbox' ";
                   1921: 	if ($anytime) {
                   1922: 	    $result.=' checked="checked" '
                   1923: 	}
1.188     raeburn  1924:         my $anytimetext = &mt('Any time');
                   1925:         if (($var eq 'startreserve') || ($var eq 'endreserve')) {
                   1926:             $anytimetext = &mt('Any time before slot starts');
                   1927:         } elsif (($var eq 'startunique') || ($var eq 'endunique')) {
                   1928:             $anytimetext = &mt('No restriction on uniqueness');     
                   1929:         }
                   1930: 	$result.="name='${var}anytime'/>".$anytimetext.'</label>'
1.118     albertel 1931:     }
1.5       bowersj2 1932:     return $result;
                   1933: 
                   1934: }
                   1935: # If a NEXTSTATE was given, switch to it
                   1936: sub postprocess {
                   1937:     my $self = shift;
                   1938:     my $var = $self->{'variable'};
1.118     albertel 1939:     if ($env{'form.' . $var . 'anytime'}) {
                   1940: 	$helper->{VARS}->{$var} = undef;
                   1941:     } else {
1.166     raeburn  1942: 	my $month = $env{'form.' . $var . 'month'};
                   1943:         $month ++;
1.118     albertel 1944: 	my $day = $env{'form.' . $var . 'day'}; 
                   1945: 	my $year = $env{'form.' . $var . 'year'}; 
                   1946: 	my $min = 0; 
                   1947: 	my $hour = 0;
                   1948: 	if ($self->{'hoursminutes'}) {
                   1949: 	    $min = $env{'form.' . $var . 'minute'};
                   1950: 	    $hour = $env{'form.' . $var . 'hour'};
                   1951: 	}
                   1952: 
1.166     raeburn  1953: 	my ($chosenDate,$checkDate);
                   1954:         my $timezone = &Apache::lonlocal::gettimezone();
                   1955:         my $dt;
                   1956: 	eval {
                   1957:                $dt = DateTime->new( year   => $year,
                   1958:                                     month  => $month,
                   1959:                                     day    => $day,
                   1960:                                     hour   => $hour,
                   1961:                                     minute => $min,
                   1962:                                     second => 0,
                   1963:                                     time_zone => $timezone,
                   1964:                              );
                   1965:         };
                   1966: 
1.118     albertel 1967: 	my $error = $@;
1.166     raeburn  1968:         if (!$error) {
                   1969:             $chosenDate  = $dt->epoch;
                   1970:             $checkDate = &get_date_object($chosenDate);
                   1971:         }
1.118     albertel 1972: 
                   1973: 	# Check to make sure that the date was not automatically co-erced into a 
                   1974: 	# valid date, as we want to flag that as an error
                   1975: 	# This happens for "Feb. 31", for instance, which is coerced to March 2 or
                   1976: 	# 3, depending on if it's a leap year
                   1977: 	
                   1978: 	if ($error || $checkDate->mon != $month || $checkDate->mday != $day ||
1.166     raeburn  1979: 	    $checkDate->year != $year) {
1.118     albertel 1980: 	    unless (Apache::lonlocal::current_language()== ~/^en/) {
                   1981: 		$self->{ERROR_MSG} = &mt("Invalid date entry");
                   1982: 		return 0;
                   1983: 	    }
                   1984: 	    # LOCALIZATION FIXME: Needs to be parameterized
1.166     raeburn  1985: 	    $self->{ERROR_MSG} = "Can't use ".$months[$env{'form.'.$var.'month'}].                                 " $day, $year as a ".
                   1986: 		                 "date because it doesn't exist. Please enter a valid date.";
1.5       bowersj2 1987: 
1.57      albertel 1988: 	    return 0;
                   1989: 	}
1.118     albertel 1990: 	$helper->{VARS}->{$var} = $chosenDate;
1.5       bowersj2 1991:     }
                   1992: 
1.137     albertel 1993:     if (defined($self->{VALIDATOR})) {
                   1994: 	my $validator = eval($self->{VALIDATOR});
1.138     albertel 1995: 	die 'Died during evaluation of validator code; Perl said: ' . $@ if $@;
1.137     albertel 1996: 	my $invalid = &$validator($helper, $state, $self, $self->getValue());
                   1997: 	if ($invalid) {
                   1998: 	    $self->{ERROR_MSG} = $invalid;
                   1999: 	    return 0;
                   2000: 	}
                   2001:     }
                   2002: 
1.5       bowersj2 2003:     if (defined($self->{NEXTSTATE})) {
                   2004:         $helper->changeState($self->{NEXTSTATE});
                   2005:     }
1.6       bowersj2 2006: 
                   2007:     return 1;
1.5       bowersj2 2008: }
1.166     raeburn  2009: 
                   2010: sub get_date_object {
                   2011:     my ($epoch) = @_;
                   2012:     my $dt = DateTime->from_epoch(epoch => $epoch)
                   2013:                      ->set_time_zone(&Apache::lonlocal::gettimezone());
                   2014:     my $lang = Apache::lonlocal::current_language();
                   2015:     if ($lang ne '') {
                   2016:         eval {
                   2017:             $dt->set_locale($lang);
                   2018:         };
                   2019:     }
                   2020:     return $dt;
                   2021: }
                   2022: 
1.5       bowersj2 2023: 1;
                   2024: 
                   2025: package Apache::lonhelper::resource;
                   2026: 
                   2027: =pod
                   2028: 
1.44      bowersj2 2029: =head2 Element: resourceX<resource, helper element>
1.5       bowersj2 2030: 
                   2031: <resource> elements allow the user to select one or multiple resources
                   2032: from the current course. You can filter out which resources they can view,
                   2033: and filter out which resources they can select. The course will always
                   2034: be displayed fully expanded, because of the difficulty of maintaining
                   2035: selections across folder openings and closings. If this is fixed, then
                   2036: the user can manipulate the folders.
                   2037: 
                   2038: <resource> takes the standard variable attribute to control what helper
1.44      bowersj2 2039: variable stores the results. It also takes a "multichoice"X<multichoice> attribute,
1.17      bowersj2 2040: which controls whether the user can select more then one resource. The 
                   2041: "toponly" attribute controls whether the resource display shows just the
                   2042: resources in that sequence, or recurses into all sub-sequences, defaulting
1.29      bowersj2 2043: to false. The "suppressEmptySequences" attribute reflects the 
                   2044: suppressEmptySequences argument to the render routine, which will cause
                   2045: folders that have all of their contained resources filtered out to also
1.46      bowersj2 2046: be filtered out. The 'addstatus' attribute, if true, will add the icon
1.95      albertel 2047: and long status display columns to the display. The 'addparts'
                   2048: attribute will add in a part selector beside problems that have more
1.163     albertel 2049: than 1 part. The 'includecourse' attribute if true, will include
                   2050: the toplevel default.sequence in the results.
1.5       bowersj2 2051: 
1.44      bowersj2 2052: =head3 SUB-TAGS
1.5       bowersj2 2053: 
                   2054: =over 4
                   2055: 
1.44      bowersj2 2056: =item * <filterfunc>X<filterfunc>: If you want to filter what resources are displayed
1.5       bowersj2 2057:   to the user, use a filter func. The <filterfunc> tag should contain
                   2058:   Perl code that when wrapped with "sub { my $res = shift; " and "}" is 
                   2059:   a function that returns true if the resource should be displayed, 
                   2060:   and false if it should be skipped. $res is a resource object. 
                   2061:   (See Apache::lonnavmaps documentation for information about the 
                   2062:   resource object.)
                   2063: 
1.44      bowersj2 2064: =item * <choicefunc>X<choicefunc>: Same as <filterfunc>, except that controls whether
1.5       bowersj2 2065:   the given resource can be chosen. (It is almost always a good idea to
                   2066:   show the user the folders, for instance, but you do not always want to 
                   2067:   let the user select them.)
                   2068: 
                   2069: =item * <nextstate>: Standard nextstate behavior.
                   2070: 
1.44      bowersj2 2071: =item * <valuefunc>X<valuefunc>: This function controls what is returned by the resource
1.5       bowersj2 2072:   when the user selects it. Like filterfunc and choicefunc, it should be
                   2073:   a function fragment that when wrapped by "sub { my $res = shift; " and
                   2074:   "}" returns a string representing what you want to have as the value. By
                   2075:   default, the value will be the resource ID of the object ($res->{ID}).
                   2076: 
1.44      bowersj2 2077: =item * <mapurl>X<mapurl>: If the URL of a map is given here, only that map
1.48      bowersj2 2078:   will be displayed, instead of the whole course. If the attribute
                   2079:   "evaluate" is given and is true, the contents of the mapurl will be
                   2080:   evaluated with "sub { my $helper = shift; my $state = shift;" and
                   2081:   "}", with the return value used as the mapurl.
1.13      bowersj2 2082: 
1.178     foxr     2083: =item * <option />: Allows you to add optional elements to the
                   2084:   resource chooser currently these can be a checkbox, or a text entry
                   2085:   or hidden (see the 'type' attribute below).
                   2086:   the following attributes are supported by this tag:
                   2087: 
                   2088: =over 4
                   2089: 
                   2090: =item * type=control-type : determines the type of control displayed.
                   2091:   This can be one of the following types: 'checkbox' provides a true/false
                   2092:   checkbox.  'text' provides a text entry control. 'hidden' provides a
                   2093:   hidden form element that returns the name of the resource for each
                   2094:   element of the text box.
                   2095: 
                   2096: =item * text=header-text : provides column header text for the option.
                   2097:   
                   2098: =item * variable=helpervar : provides a helper variable to contain the
                   2099:   value of the input control for each resource.  In general, the result
                   2100:   will be a set of values separated by |||  for the checkbox the value between
                   2101:   the |||'s will either be empty, if the box is not checked, or the resource
                   2102:   name if checked.  For the text entry, the values will be the text in the
                   2103:   text box.  This could be empty.  Hidden elements unconditionally provide
                   2104:   the resource name for each row of the chooser and allow you to therefore
                   2105:   correlate text entries to their resources.
                   2106:   The helper variable can be initialized by the user code to pre-load values
                   2107:   into the controls:
                   2108: 
                   2109: =over 4
                   2110: 
                   2111:   
                   2112: =item * Preloading checkboxes : Set the helper variable to the value you
                   2113:    would have gotten from the control if it had been manually set as desired.
                   2114: 
                   2115: =item * Preloading text entries : Set the helper variable to triple pipe
                   2116:    separated values where each value is of the form resource-name=value
                   2117: 
                   2118: =item * Preloading hidden fields : These cannot be pre-loaded and will always
                   2119:   be pipe separated resource names.
                   2120: 
                   2121: =back
                   2122: 
                   2123: 
                   2124: =back
                   2125: 
1.5       bowersj2 2126: =back
                   2127: 
                   2128: =cut
                   2129: 
                   2130: no strict;
                   2131: @ISA = ("Apache::lonhelper::element");
                   2132: use strict;
1.100     albertel 2133: use Apache::lonnet;
1.5       bowersj2 2134: 
                   2135: BEGIN {
1.7       bowersj2 2136:     &Apache::lonhelper::register('Apache::lonhelper::resource',
1.5       bowersj2 2137:                               ('resource', 'filterfunc', 
1.13      bowersj2 2138:                                'choicefunc', 'valuefunc',
1.90      foxr     2139:                                'mapurl','option'));
1.5       bowersj2 2140: }
                   2141: 
                   2142: sub new {
                   2143:     my $ref = Apache::lonhelper::element->new();
                   2144:     bless($ref);
                   2145: }
                   2146: 
                   2147: # CONSTRUCTION: Construct the message element from the XML
                   2148: sub start_resource {
                   2149:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2150: 
                   2151:     if ($target ne 'helper') {
                   2152:         return '';
                   2153:     }
                   2154: 
                   2155:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   2156:     $helper->declareVar($paramHash->{'variable'});
1.14      bowersj2 2157:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.29      bowersj2 2158:     $paramHash->{'suppressEmptySequences'} = $token->[2]{'suppressEmptySequences'};
1.17      bowersj2 2159:     $paramHash->{'toponly'} = $token->[2]{'toponly'};
1.46      bowersj2 2160:     $paramHash->{'addstatus'} = $token->[2]{'addstatus'};
1.95      albertel 2161:     $paramHash->{'addparts'} = $token->[2]{'addparts'};
                   2162:     if ($paramHash->{'addparts'}) {
                   2163: 	$helper->declareVar($paramHash->{'variable'}.'_part');
                   2164:     }
1.66      albertel 2165:     $paramHash->{'closeallpages'} = $token->[2]{'closeallpages'};
1.163     albertel 2166:     $paramHash->{'include_top_level_map'} = $token->[2]{'includecourse'};
1.5       bowersj2 2167:     return '';
                   2168: }
                   2169: 
                   2170: sub end_resource {
                   2171:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2172: 
                   2173:     if ($target ne 'helper') {
                   2174:         return '';
                   2175:     }
                   2176:     if (!defined($paramHash->{FILTER_FUNC})) {
                   2177:         $paramHash->{FILTER_FUNC} = sub {return 1;};
                   2178:     }
                   2179:     if (!defined($paramHash->{CHOICE_FUNC})) {
                   2180:         $paramHash->{CHOICE_FUNC} = sub {return 1;};
                   2181:     }
                   2182:     if (!defined($paramHash->{VALUE_FUNC})) {
                   2183:         $paramHash->{VALUE_FUNC} = sub {my $res = shift; return $res->{ID}; };
                   2184:     }
                   2185:     Apache::lonhelper::resource->new();
1.4       bowersj2 2186:     return '';
                   2187: }
                   2188: 
1.5       bowersj2 2189: sub start_filterfunc {
                   2190:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2191: 
                   2192:     if ($target ne 'helper') {
                   2193:         return '';
                   2194:     }
                   2195: 
                   2196:     my $contents = Apache::lonxml::get_all_text('/filterfunc',
                   2197:                                                 $parser);
                   2198:     $contents = 'sub { my $res = shift; ' . $contents . '}';
                   2199:     $paramHash->{FILTER_FUNC} = eval $contents;
                   2200: }
                   2201: 
                   2202: sub end_filterfunc { return ''; }
                   2203: 
                   2204: sub start_choicefunc {
                   2205:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2206: 
                   2207:     if ($target ne 'helper') {
                   2208:         return '';
                   2209:     }
                   2210: 
                   2211:     my $contents = Apache::lonxml::get_all_text('/choicefunc',
                   2212:                                                 $parser);
                   2213:     $contents = 'sub { my $res = shift; ' . $contents . '}';
                   2214:     $paramHash->{CHOICE_FUNC} = eval $contents;
                   2215: }
                   2216: 
                   2217: sub end_choicefunc { return ''; }
                   2218: 
                   2219: sub start_valuefunc {
                   2220:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2221: 
                   2222:     if ($target ne 'helper') {
                   2223:         return '';
                   2224:     }
                   2225: 
                   2226:     my $contents = Apache::lonxml::get_all_text('/valuefunc',
                   2227:                                                 $parser);
                   2228:     $contents = 'sub { my $res = shift; ' . $contents . '}';
                   2229:     $paramHash->{VALUE_FUNC} = eval $contents;
                   2230: }
                   2231: 
                   2232: sub end_valuefunc { return ''; }
                   2233: 
1.13      bowersj2 2234: sub start_mapurl {
                   2235:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2236: 
                   2237:     if ($target ne 'helper') {
                   2238:         return '';
                   2239:     }
                   2240: 
                   2241:     my $contents = Apache::lonxml::get_all_text('/mapurl',
                   2242:                                                 $parser);
1.48      bowersj2 2243:     $paramHash->{EVAL_MAP_URL} = $token->[2]{'evaluate'};
1.14      bowersj2 2244:     $paramHash->{MAP_URL} = $contents;
1.13      bowersj2 2245: }
                   2246: 
                   2247: sub end_mapurl { return ''; }
                   2248: 
1.90      foxr     2249: 
                   2250: sub start_option {
                   2251:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2252:     if (!defined($paramHash->{OPTION_TEXTS})) {
                   2253: 	$paramHash->{OPTION_TEXTS} = [ ];
                   2254: 	$paramHash->{OPTION_VARS}  = [ ];
1.177     foxr     2255: 	$paramHash->{OPTION_TYPES} = [ ];
1.91      foxr     2256: 
1.90      foxr     2257:     }
1.177     foxr     2258:     #  We can have an attribute: type which can have the
                   2259:     #  values: "checkbox" or "text" which defaults to 
                   2260:     #           checkbox allowing us to change the type of input
                   2261:     #           for the option:
                   2262:     #
                   2263:     my $input_widget_type = 'checkbox';
                   2264:     if(defined($token->[2]{'type'})) {
                   2265: 	my $widget_type  = $token->[2]{'type'};
                   2266: 	if ($widget_type eq 'text') {          # only accept legal alternatives
                   2267: 	    $input_widget_type = $widget_type; # Illegals are checks.
                   2268: 	} elsif ($widget_type eq 'hidden') {
                   2269: 	    $input_widget_type = $widget_type;
                   2270: 	}
                   2271:     }
                   2272: 
1.91      foxr     2273:     # OPTION_TEXTS is a list of the text attribute
                   2274:     #               values used to create column headings.
                   2275:     # OPTION_VARS is a list of the variable names, used to create the checkbox
                   2276:     #             inputs.
1.177     foxr     2277:     # OPTION_TYPES is a list of the option types:
                   2278:     #
1.90      foxr     2279:     #  We're ok with empty elements. as place holders
                   2280:     # Although the 'variable' element should really exist.
1.91      foxr     2281:     #
                   2282: 
1.177     foxr     2283: 
1.90      foxr     2284:     my $option_texts  = $paramHash->{OPTION_TEXTS};
                   2285:     my $option_vars   = $paramHash->{OPTION_VARS};
1.177     foxr     2286:     my $option_types   = $paramHash->{OPTION_TYPES};
1.90      foxr     2287:     push(@$option_texts,  $token->[2]{'text'});
                   2288:     push(@$option_vars,   $token->[2]{'variable'});
1.177     foxr     2289:     push(@$option_types,   $input_widget_type);
                   2290: 
1.90      foxr     2291: 
1.91      foxr     2292:     #  Need to create and declare the option variables as well to make them
                   2293:     # persistent.
                   2294:     #
                   2295:     my $varname = $token->[2]{'variable'};
                   2296:     $helper->declareVar($varname);
                   2297: 
                   2298: 
1.90      foxr     2299:     return '';
                   2300: }
                   2301: 
                   2302: sub end_option {
                   2303:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2304:     return '';
                   2305: }
                   2306: 
1.5       bowersj2 2307: # A note, in case I don't get to this before I leave.
                   2308: # If someone complains about the "Back" button returning them
                   2309: # to the previous folder state, instead of returning them to
                   2310: # the previous helper state, the *correct* answer is for the helper
                   2311: # to keep track of how many times the user has manipulated the folders,
                   2312: # and feed that to the history.go() call in the helper rendering routines.
                   2313: # If done correctly, the helper itself can keep track of how many times
                   2314: # it renders the same states, so it doesn't go in just this state, and
                   2315: # you can lean on the browser back button to make sure it all chains
                   2316: # correctly.
                   2317: # Right now, though, I'm just forcing all folders open.
                   2318: 
                   2319: sub render {
                   2320:     my $self = shift;
                   2321:     my $result = "";
                   2322:     my $var = $self->{'variable'};
                   2323:     my $curVal = $helper->{VARS}->{$var};
                   2324: 
1.15      bowersj2 2325:     my $buttons = '';
                   2326: 
                   2327:     if ($self->{'multichoice'}) {
                   2328:         $result = <<SCRIPT;
1.112     albertel 2329: <script type="text/javascript">
                   2330: // <!--
1.18      bowersj2 2331:     function checkall(value, checkName) {
1.15      bowersj2 2332: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
                   2333:             ele = document.forms.helpform.elements[i];
1.157     raeburn  2334:             if (ele.name == checkName + '_forminput') {
1.15      bowersj2 2335:                 document.forms.helpform.elements[i].checked=value;
                   2336:             }
                   2337:         }
                   2338:     }
1.112     albertel 2339: // -->
1.15      bowersj2 2340: </script>
                   2341: SCRIPT
1.68      sakharuk 2342:         my %lt=&Apache::lonlocal::texthash(
                   2343: 			'sar'  => "Select All Resources",
                   2344: 		        'uar'  => "Unselect All Resources");
                   2345: 
1.15      bowersj2 2346:         $buttons = <<BUTTONS;
                   2347: <br /> &nbsp;
1.68      sakharuk 2348: <input type="button" onclick="checkall(true, '$var')" value="$lt{'sar'}" />
                   2349: <input type="button" onclick="checkall(false, '$var')" value="$lt{'uar'}" />
1.15      bowersj2 2350: <br /> &nbsp;
                   2351: BUTTONS
                   2352:     }
                   2353: 
1.5       bowersj2 2354:     if (defined $self->{ERROR_MSG}) {
1.14      bowersj2 2355:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
1.5       bowersj2 2356:     }
                   2357: 
1.15      bowersj2 2358:     $result .= $buttons;
                   2359: 
1.90      foxr     2360:     my $filterFunc     = $self->{FILTER_FUNC};
                   2361:     my $choiceFunc     = $self->{CHOICE_FUNC};
                   2362:     my $valueFunc      = $self->{VALUE_FUNC};
1.95      albertel 2363:     my $multichoice    = $self->{'multichoice'};
1.90      foxr     2364:     my $option_vars    = $self->{OPTION_VARS};
                   2365:     my $option_texts   = $self->{OPTION_TEXTS};
1.177     foxr     2366:     my $option_types   = $self->{OPTION_TYPES};
1.95      albertel 2367:     my $addparts       = $self->{'addparts'};
1.90      foxr     2368:     my $headings_done  = 0;
1.5       bowersj2 2369: 
1.48      bowersj2 2370:     # Evaluate the map url as needed
                   2371:     my $mapUrl;
1.49      bowersj2 2372:     if ($self->{EVAL_MAP_URL}) {
1.48      bowersj2 2373: 	my $mapUrlFunc = eval('sub { my $helper = shift; my $state = shift; ' . 
                   2374: 	    $self->{MAP_URL} . '}');
                   2375: 	$mapUrl = &$mapUrlFunc($helper, $self);
                   2376:     } else {
                   2377: 	$mapUrl = $self->{MAP_URL};
                   2378:     }
                   2379: 
1.125     albertel 2380:     my %defaultSymbs;
1.124     albertel 2381:     if (defined($self->{DEFAULT_VALUE})) {
                   2382:         my $valueFunc = eval($self->{DEFAULT_VALUE});
                   2383:         die 'Error in default value code for variable ' . 
                   2384:             $self->{'variable'} . ', Perl said: ' . $@ if $@;
1.125     albertel 2385:         my @defaultSymbs = &$valueFunc($helper, $self);
                   2386: 	if (!$multichoice && @defaultSymbs) { # only allowed 1
1.124     albertel 2387: 	    @defaultSymbs = ($defaultSymbs[0]);
                   2388: 	}
1.125     albertel 2389: 	%defaultSymbs = map { if ($_) {($_,1) } } @defaultSymbs;
                   2390: 	delete($defaultSymbs{''});
1.124     albertel 2391:     }
                   2392: 
1.5       bowersj2 2393:     # Create the composite function that renders the column on the nav map
                   2394:     # have to admit any language that lets me do this can't be all bad
                   2395:     #  - Jeremy (Pythonista) ;-)
                   2396:     my $checked = 0;
                   2397:     my $renderColFunc = sub {
                   2398:         my ($resource, $part, $params) = @_;
1.90      foxr     2399: 	my $result = "";
                   2400: 
                   2401: 	if(!$headings_done) {
                   2402: 	    if ($option_texts) {
                   2403: 		foreach my $text (@$option_texts) {
                   2404: 		    $result .= "<th>$text</th>";
                   2405: 		}
                   2406: 	    }
1.192     bisitz   2407: 	    $result .= '<th>'.&Apache::lonlocal::mt('Select').'</th>';
1.90      foxr     2408: 	    $result .= "</tr><tr>"; # Close off the extra row and start a new one.
                   2409: 	    $headings_done = 1;
                   2410: 	}
1.14      bowersj2 2411: 
                   2412:         my $inputType;
                   2413:         if ($multichoice) { $inputType = 'checkbox'; }
                   2414:         else {$inputType = 'radio'; }
                   2415: 
1.5       bowersj2 2416:         if (!&$choiceFunc($resource)) {
1.90      foxr     2417: 	    $result .= '<td>&nbsp;</td>';
                   2418:             return $result;
1.5       bowersj2 2419:         } else {
1.90      foxr     2420: 	    my $col = "";
1.98      foxr     2421: 	    my $raw_name = &$valueFunc($resource);
1.90      foxr     2422: 	    my $resource_name =   
1.98      foxr     2423:                    HTML::Entities::encode($raw_name,"<>&\"'");
1.90      foxr     2424: 	    if($option_vars) {
1.177     foxr     2425: 		my $option_num = 0;
1.91      foxr     2426: 		foreach my $option_var (@$option_vars) {
1.177     foxr     2427: 		    my $option_type = $option_types->[$option_num];
                   2428: 		    $option_num++;
1.99      foxr     2429: 		    my $var_value = "\|\|\|" . $helper->{VARS}->{$option_var} . 
                   2430: 			"\|\|\|";
1.98      foxr     2431: 		    my $checked ="";
1.99      foxr     2432: 		    if($var_value =~ /\Q|||$raw_name|||\E/) {
1.111     albertel 2433: 			$checked = "checked='checked'";
1.98      foxr     2434: 		    }
1.177     foxr     2435: 		    if ($option_type eq 'text') {
                   2436: 			#
                   2437: 			# For text's the variable value is a ||| separated set of
                   2438: 			# resource_name=value 
                   2439: 			#
                   2440: 			my @values = split(/\|\|\|/, $helper->{VARS}->{$option_var});
                   2441: 
                   2442: 			# Normal practice would be to toss this in a hash but 
                   2443: 			# the only thing that saves is the compare in the loop
                   2444: 			# below and for all but one case we'll break out of the loop
                   2445: 			# before it completes.
                   2446: 
                   2447: 			my $text_value = '';    # In case there's no match.
                   2448: 			foreach my $value (@values) {
                   2449: 			    my ($res, $skip) = split(/=/, $value);
                   2450: 			    if($res eq $resource_name) {
                   2451: 				$text_value = $skip;
                   2452: 				last;
                   2453: 			    }
                   2454: 			}
1.178     foxr     2455: 			# TODO: add an attribute to <option> that allows the
                   2456: 			#       programmer to set the width of the tex entry box.
1.177     foxr     2457: 
                   2458: 			$col .=
                   2459: 			    "<td align='center'><input type='text' name ='$option_var".
                   2460: 			    "_forminput' value='".$text_value."' size='5' /> </td>";
                   2461: 		    } elsif ($option_type eq 'hidden') {
                   2462:  			$col .= "<td align='center'><input type='hidden' name ='$option_var".
                   2463: 			    "_forminput' value='".
                   2464: 			    $resource_name . "'/> </td>";
                   2465: 		    } else {
                   2466: 			$col .= 
                   2467: 			    "<td align='center'><input type=$option_type name ='$option_var".
                   2468: 			    "_forminput' value='".
                   2469: 			    $resource_name . "' $checked /> </td>";
                   2470: 		    }
1.90      foxr     2471: 		}
                   2472: 	    }
                   2473: 
1.157     raeburn  2474:             $col .= "<td align='center'><input type='$inputType' name='${var}_forminput' ";
1.125     albertel 2475: 	    if (%defaultSymbs) {
1.124     albertel 2476: 		my $symb=$resource->symb();
1.125     albertel 2477: 		if (exists($defaultSymbs{$symb})) {
1.124     albertel 2478: 		    $col .= "checked='checked' ";
                   2479: 		    $checked = 1;
                   2480: 		}
                   2481: 	    } else {
                   2482: 		if (!$checked && !$multichoice) {
                   2483: 		    $col .= "checked='checked' ";
                   2484: 		    $checked = 1;
                   2485: 		}
                   2486: 		if ($multichoice) { # all resources start checked; see bug 1174
                   2487: 		    $col .= "checked='checked' ";
                   2488: 		    $checked = 1;
                   2489: 		}
1.37      bowersj2 2490: 	    }
1.90      foxr     2491:             $col .= "value='" . $resource_name  . "' /></td>";
1.95      albertel 2492: 
1.90      foxr     2493:             return $result.$col;
1.5       bowersj2 2494:         }
                   2495:     };
1.95      albertel 2496:     my $renderPartsFunc = sub {
                   2497:         my ($resource, $part, $params) = @_;
                   2498: 	my $col= "<td>";
                   2499: 	my $id=$resource->{ID};
                   2500: 	my $resource_name =   
                   2501: 	    &HTML::Entities::encode(&$valueFunc($resource),"<>&\"'");
                   2502: 	if ($addparts && (scalar(@{$resource->parts}) > 1)) {
1.157     raeburn  2503: 	    $col .= "<select onclick=\"javascript:updateRadio(this.form,'${var}_forminput','$resource_name');updateHidden(this.form,'$id','${var}');\" name='part_${id}_forminput'>\n";
1.194     raeburn  2504: 	    $col .= "<option value=\"$part\">".&Apache::lonlocal::mt('All Parts')."</option>\n";
1.95      albertel 2505: 	    foreach my $part (@{$resource->parts}) {
1.192     bisitz   2506: 		$col .= "<option value=\"$part\">".&Apache::lonlocal::mt('Part: [_1]',$part)."</option>\n";
1.95      albertel 2507: 	    }
                   2508: 	    $col .= "</select>";
                   2509: 	}
                   2510: 	$col .= "</td>";
                   2511:     };
                   2512:     $result.=(<<RADIO);
                   2513: <script type="text/javascript">
1.112     albertel 2514: // <!--
1.95      albertel 2515:     function updateRadio(form,name,value) {
                   2516: 	var radiobutton=form[name];
                   2517: 	for (var i=0; i<radiobutton.length; i++) {
                   2518: 	    if (radiobutton[i].value == value) {
                   2519: 		radiobutton[i].checked = true;
                   2520: 		break;
                   2521: 	    }
                   2522: 	}
                   2523:     }
                   2524:     function updateHidden(form,id,name) {
1.157     raeburn  2525: 	var select=form['part_'+id+'_forminput'];
                   2526: 	var hidden=form[name+'_part_forminput'];
1.95      albertel 2527: 	var which=select.selectedIndex;
                   2528: 	hidden.value=select.options[which].value;
                   2529:     }
1.112     albertel 2530: // -->
1.95      albertel 2531: </script>
1.157     raeburn  2532: <input type="hidden" name="${var}_part_forminput" />
1.5       bowersj2 2533: 
1.95      albertel 2534: RADIO
1.100     albertel 2535:     $env{'form.condition'} = !$self->{'toponly'};
1.95      albertel 2536:     my $cols = [$renderColFunc];
                   2537:     if ($self->{'addparts'}) { push(@$cols, $renderPartsFunc); }
                   2538:     push(@$cols, Apache::lonnavmaps::resource());
1.46      bowersj2 2539:     if ($self->{'addstatus'}) {
                   2540: 	push @$cols, (Apache::lonnavmaps::part_status_summary());
                   2541: 	
                   2542:     }
1.5       bowersj2 2543:     $result .= 
1.46      bowersj2 2544:         &Apache::lonnavmaps::render( { 'cols' => $cols,
1.5       bowersj2 2545:                                        'showParts' => 0,
                   2546:                                        'filterFunc' => $filterFunc,
1.13      bowersj2 2547:                                        'resource_no_folder_link' => 1,
1.66      albertel 2548: 				       'closeAllPages' => $self->{'closeallpages'},
1.29      bowersj2 2549:                                        'suppressEmptySequences' => $self->{'suppressEmptySequences'},
1.163     albertel 2550: 				       'include_top_level_map' => $self->{'include_top_level_map'},
1.190     raeburn  2551:                                        'iterator_map' => $mapUrl,
                   2552:                                        'map_no_edit_link' => 1, } 
1.5       bowersj2 2553:                                        );
1.15      bowersj2 2554: 
                   2555:     $result .= $buttons;
1.5       bowersj2 2556:                                                 
                   2557:     return $result;
                   2558: }
                   2559:     
                   2560: sub postprocess {
                   2561:     my $self = shift;
1.14      bowersj2 2562: 
                   2563:     if ($self->{'multichoice'} && !$helper->{VARS}->{$self->{'variable'}}) {
                   2564:         $self->{ERROR_MSG} = 'You must choose at least one resource to continue.';
                   2565:         return 0;
                   2566:     }
1.171     foxr     2567:     # For each of the attached options.  If it's env var is undefined, set it to
                   2568:     # an empty string instead.. an undef'd env var means no choices selected.
                   2569:     #
                   2570: 
                   2571:     my $option_vars = $self->{OPTION_VARS};
                   2572:     if ($option_vars) {
                   2573: 	foreach my $var (@$option_vars) {
                   2574: 	    my $env_name = "form.".$var."_forminput";
                   2575: 	    if (!defined($env{$env_name})) {
                   2576: 		$env{$env_name} = '';
                   2577: 		$helper->{VARS}->{$var} = '';
                   2578: 	    }
                   2579: 	}
                   2580:     }
                   2581: 
1.14      bowersj2 2582: 
1.5       bowersj2 2583:     if (defined($self->{NEXTSTATE})) {
                   2584:         $helper->changeState($self->{NEXTSTATE});
                   2585:     }
1.6       bowersj2 2586: 
                   2587:     return 1;
1.5       bowersj2 2588: }
                   2589: 
                   2590: 1;
                   2591: 
                   2592: package Apache::lonhelper::student;
                   2593: 
                   2594: =pod
                   2595: 
1.44      bowersj2 2596: =head2 Element: studentX<student, helper element>
1.5       bowersj2 2597: 
                   2598: Student elements display a choice of students enrolled in the current
                   2599: course. Currently it is primitive; this is expected to evolve later.
                   2600: 
1.48      bowersj2 2601: Student elements take the following attributes: 
                   2602: 
                   2603: =over 4
                   2604: 
                   2605: =item * B<variable>: 
                   2606: 
                   2607: Does what it usually does: declare which helper variable to put the
                   2608: result in.
                   2609: 
                   2610: =item * B<multichoice>: 
                   2611: 
                   2612: If true allows the user to select multiple students. Defaults to false.
                   2613: 
                   2614: =item * B<coursepersonnel>: 
                   2615: 
                   2616: If true adds the course personnel to the top of the student
                   2617: selection. Defaults to false.
                   2618: 
                   2619: =item * B<activeonly>:
                   2620: 
                   2621: If true, only active students and course personnel will be
                   2622: shown. Defaults to false.
                   2623: 
1.196   ! raeburn  2624: =item * B<sectiononly>:
        !          2625: 
        !          2626: If true, and user's role is in a specific section, only course personnel 
        !          2627: will be shown if they also have a section-specific role in the same section.
        !          2628: Defaults to false.
        !          2629: 
1.123     albertel 2630: =item * B<emptyallowed>:
                   2631: 
                   2632: If true, the selection of no users is allowed. Defaults to false.
                   2633: 
1.48      bowersj2 2634: =back
1.5       bowersj2 2635: 
                   2636: =cut
                   2637: 
                   2638: no strict;
                   2639: @ISA = ("Apache::lonhelper::element");
                   2640: use strict;
1.59      bowersj2 2641: use Apache::lonlocal;
1.100     albertel 2642: use Apache::lonnet;
1.139     foxr     2643: 
1.5       bowersj2 2644: BEGIN {
1.7       bowersj2 2645:     &Apache::lonhelper::register('Apache::lonhelper::student',
1.5       bowersj2 2646:                               ('student'));
                   2647: }
                   2648: 
                   2649: sub new {
                   2650:     my $ref = Apache::lonhelper::element->new();
                   2651:     bless($ref);
                   2652: }
1.4       bowersj2 2653: 
1.5       bowersj2 2654: sub start_student {
1.4       bowersj2 2655:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2656: 
                   2657:     if ($target ne 'helper') {
                   2658:         return '';
                   2659:     }
                   2660: 
1.5       bowersj2 2661:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   2662:     $helper->declareVar($paramHash->{'variable'});
                   2663:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.39      bowersj2 2664:     $paramHash->{'coursepersonnel'} = $token->[2]{'coursepersonnel'};
1.196   ! raeburn  2665:     $paramHash->{'sectiononly'} = $token->[2]{'sectiononly'};
1.93      albertel 2666:     $paramHash->{'activeonly'} = $token->[2]{'activeonly'};
1.12      bowersj2 2667:     if (defined($token->[2]{'nextstate'})) {
                   2668:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
                   2669:     }
1.123     albertel 2670:     $paramHash->{'emptyallowed'} = $token->[2]{'emptyallowed'};
1.12      bowersj2 2671:     
1.5       bowersj2 2672: }    
                   2673: 
                   2674: sub end_student {
                   2675:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2676: 
                   2677:     if ($target ne 'helper') {
                   2678:         return '';
                   2679:     }
                   2680:     Apache::lonhelper::student->new();
1.3       bowersj2 2681: }
1.5       bowersj2 2682: 
                   2683: sub render {
                   2684:     my $self = shift;
                   2685:     my $result = '';
                   2686:     my $buttons = '';
1.18      bowersj2 2687:     my $var = $self->{'variable'};
1.5       bowersj2 2688: 
                   2689: 
                   2690:     if (defined $self->{ERROR_MSG}) {
                   2691:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   2692:     }
                   2693: 
1.126     albertel 2694:     my %defaultUsers;
                   2695:     if (defined($self->{DEFAULT_VALUE})) {
                   2696:         my $valueFunc = eval($self->{DEFAULT_VALUE});
                   2697:         die 'Error in default value code for variable ' . 
                   2698:             $self->{'variable'} . ', Perl said: ' . $@ if $@;
                   2699:         my @defaultUsers = &$valueFunc($helper, $self);
                   2700: 	if (!$self->{'multichoice'} && @defaultUsers) { # only allowed 1
                   2701: 	    @defaultUsers = ($defaultUsers[0]);
                   2702: 	}
                   2703: 	%defaultUsers = map { if ($_) {($_,1) } } @defaultUsers;
                   2704: 	delete($defaultUsers{''});
                   2705:     }
1.139     foxr     2706: 
1.196   ! raeburn  2707:     my $personnel_section;
        !          2708:     if ($self->{'sectiononly'}) {
        !          2709:         $personnel_section = $env{'request.course.sec'};
        !          2710:     }
        !          2711: 
1.147     foxr     2712:     my ($course_personnel, 
                   2713: 	$current_members, 
                   2714: 	$expired_members, 
1.153     foxr     2715: 	$future_members) = 
1.196   ! raeburn  2716: 	    &Apache::lonselstudent::get_people_in_class($env{'request.course.sec'},
        !          2717: 	                                                $personnel_section);
1.139     foxr     2718: 
1.39      bowersj2 2719:     # Load up the non-students, if necessary
1.147     foxr     2720: 
1.39      bowersj2 2721:     if ($self->{'coursepersonnel'}) {
1.147     foxr     2722: 	unshift @$current_members, (@$course_personnel);
1.39      bowersj2 2723:     }
1.5       bowersj2 2724: 
1.196   ! raeburn  2725:     my %titles = &Apache::lonlocal::texthash(
        !          2726:                    'active'  => 'Select Currently Enrolled Students and Active Course Personnel',
        !          2727:                    'future'  => 'Select Future Enrolled Students',
        !          2728:                    'expired' => 'Select Previously Enrolled Students',
        !          2729:                  );
        !          2730: 
        !          2731:     if ($env{'request.course.sec'}) {
        !          2732:         if ($self->{'sectiononly'}) {
        !          2733:             $titles{'active'} = &mt('Select Currently Enrolled Students and Active Course Personnel in Section: [_1]',
        !          2734:                                 $env{'request.course.sec'});
        !          2735:         } else {
        !          2736:             $titles{'active'} = &mt('Select Currently Enrolled Students in Section: [_1], and Active Course Personnel',
        !          2737:                                     $env{'request.course.sec'});
        !          2738:         }
        !          2739:         $titles{'future'} = &mt('Select Future Enrolled Students in Section: [_1]',
        !          2740:                                 $env{'request.course.sec'});
        !          2741:         $titles{'expired'} = &mt('Select Previously Enrolled Students in Section: [_1]',
        !          2742:                                  $env{'request.course.sec'});
        !          2743:     }
1.5       bowersj2 2744: 
1.196   ! raeburn  2745:     #   Current personnel
1.139     foxr     2746: 
1.196   ! raeburn  2747:     $result .= '<h4>'.$titles{'active'}.'</h4>';
1.148     foxr     2748:     $result .= &Apache::lonselstudent::render_student_list( $current_members,
1.149     foxr     2749: 							    "helpform",
1.196   ! raeburn  2750: 							    "current",
1.149     foxr     2751: 							    \%defaultUsers,
                   2752: 							    $self->{'multichoice'},
                   2753: 							    $self->{'variable'},
                   2754: 							    1);
1.139     foxr     2755: 
                   2756:     # If activeonly is not set then we can also give the expired students:
                   2757:     #
1.158     albertel 2758:     if (!$self->{'activeonly'} && ((scalar(@$future_members)) > 0)) {
1.132     foxr     2759: 
1.140     albertel 2760: 	# And future.
                   2761: 
1.196   ! raeburn  2762: 	$result .= '<h4>'.$titles{'future'}.'</h4>';
1.156     foxr     2763:        
1.148     foxr     2764: 	$result .= &Apache::lonselstudent::render_student_list( $future_members,
1.149     foxr     2765: 								"helpform",
                   2766: 								"future",
                   2767: 								\%defaultUsers,
                   2768: 								$self->{'multichoice'},
                   2769: 								$self->{'variable'},
                   2770: 								0);
1.158     albertel 2771:     }
                   2772:     if (!$self->{'activeonly'} && ((scalar(@$expired_members)) > 0)) {
1.139     foxr     2773: 	# Past 
1.39      bowersj2 2774: 
1.196   ! raeburn  2775: 	$result .= '<h4>'.$titles{'expired'}.'</h4>';
1.148     foxr     2776: 	$result .= &Apache::lonselstudent::render_student_list($expired_members,
1.149     foxr     2777: 							       "helpform",
                   2778: 							       "past",
                   2779: 							       \%defaultUsers,
                   2780: 							       $self->{'multichoice'},
                   2781: 							       $self->{'variable'},
                   2782: 							       0);
1.132     foxr     2783:     }
1.5       bowersj2 2784: 
1.113     foxr     2785: 
                   2786: 
1.5       bowersj2 2787:     return $result;
                   2788: }
                   2789: 
1.6       bowersj2 2790: sub postprocess {
                   2791:     my $self = shift;
                   2792: 
1.157     raeburn  2793:     my $result = $env{'form.' . $self->{'variable'} . '_forminput'};
1.123     albertel 2794:     if (!$result && !$self->{'emptyallowed'}) {
                   2795: 	if ($self->{'coursepersonnel'}) {
                   2796: 	    $self->{ERROR_MSG} = 
                   2797: 		&mt('You must choose at least one user to continue.');
                   2798: 	} else {
                   2799: 	    $self->{ERROR_MSG} = 
                   2800: 		&mt('You must choose at least one student to continue.');
                   2801: 	}
1.6       bowersj2 2802:         return 0;
                   2803:     }
                   2804: 
                   2805:     if (defined($self->{NEXTSTATE})) {
                   2806:         $helper->changeState($self->{NEXTSTATE});
                   2807:     }
                   2808: 
                   2809:     return 1;
                   2810: }
                   2811: 
1.5       bowersj2 2812: 1;
                   2813: 
                   2814: package Apache::lonhelper::files;
                   2815: 
                   2816: =pod
                   2817: 
1.44      bowersj2 2818: =head2 Element: filesX<files, helper element>
1.5       bowersj2 2819: 
                   2820: files allows the users to choose files from a given directory on the
                   2821: server. It is always multichoice and stores the result as a triple-pipe
                   2822: delimited entry in the helper variables. 
                   2823: 
                   2824: Since it is extremely unlikely that you can actually code a constant
                   2825: representing the directory you wish to allow the user to search, <files>
                   2826: takes a subroutine that returns the name of the directory you wish to
                   2827: have the user browse.
                   2828: 
                   2829: files accepts the attribute "variable" to control where the files chosen
                   2830: are put. It accepts the attribute "multichoice" as the other attribute,
                   2831: defaulting to false, which if true will allow the user to select more
                   2832: then one choice. 
                   2833: 
1.44      bowersj2 2834: <files> accepts three subtags: 
                   2835: 
                   2836: =over 4
                   2837: 
                   2838: =item * B<nextstate>: works as it does with the other tags. 
                   2839: 
                   2840: =item * B<filechoice>: When the contents of this tag are surrounded by
                   2841:     "sub {" and "}", will return a string representing what directory
                   2842:     on the server to allow the user to choose files from. 
                   2843: 
                   2844: =item * B<filefilter>: Should contain Perl code that when surrounded
                   2845:     by "sub { my $filename = shift; " and "}", returns a true value if
                   2846:     the user can pick that file, or false otherwise. The filename
                   2847:     passed to the function will be just the name of the file, with no
                   2848:     path info. By default, a filter function will be used that will
                   2849:     mask out old versions of files. This function is available as
                   2850:     Apache::lonhelper::files::not_old_version if you want to use it to
                   2851:     composite your own filters.
                   2852: 
                   2853: =back
                   2854: 
                   2855: B<General security note>: You should ensure the user can not somehow 
                   2856: pass something into your code that would allow them to look places 
                   2857: they should not be able to see, like the C</etc/> directory. However,
                   2858: the security impact would be minimal, since it would only expose
                   2859: the existence of files, there should be no way to parlay that into
                   2860: viewing the files. 
1.5       bowersj2 2861: 
                   2862: =cut
                   2863: 
                   2864: no strict;
                   2865: @ISA = ("Apache::lonhelper::element");
                   2866: use strict;
1.59      bowersj2 2867: use Apache::lonlocal;
1.100     albertel 2868: use Apache::lonnet;
1.32      bowersj2 2869: use Apache::lonpubdir; # for getTitleString
                   2870: 
1.5       bowersj2 2871: BEGIN {
1.7       bowersj2 2872:     &Apache::lonhelper::register('Apache::lonhelper::files',
                   2873:                                  ('files', 'filechoice', 'filefilter'));
1.5       bowersj2 2874: }
                   2875: 
1.44      bowersj2 2876: sub not_old_version {
                   2877:     my $file = shift;
                   2878:     
                   2879:     # Given a file name, return false if it is an "old version" of a
                   2880:     # file, or true if it is not.
                   2881: 
                   2882:     if ($file =~ /^.*\.[0-9]+\.[A-Za-z]+(\.meta)?$/) {
                   2883: 	return 0;
                   2884:     }
                   2885:     return 1;
                   2886: }
                   2887: 
1.5       bowersj2 2888: sub new {
                   2889:     my $ref = Apache::lonhelper::element->new();
                   2890:     bless($ref);
                   2891: }
                   2892: 
                   2893: sub start_files {
                   2894:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2895: 
                   2896:     if ($target ne 'helper') {
                   2897:         return '';
                   2898:     }
                   2899:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   2900:     $helper->declareVar($paramHash->{'variable'});
                   2901:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
                   2902: }    
                   2903: 
                   2904: sub end_files {
                   2905:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2906: 
                   2907:     if ($target ne 'helper') {
                   2908:         return '';
                   2909:     }
                   2910:     if (!defined($paramHash->{FILTER_FUNC})) {
                   2911:         $paramHash->{FILTER_FUNC} = sub { return 1; };
                   2912:     }
                   2913:     Apache::lonhelper::files->new();
                   2914: }    
                   2915: 
                   2916: sub start_filechoice {
                   2917:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2918: 
                   2919:     if ($target ne 'helper') {
                   2920:         return '';
                   2921:     }
                   2922:     $paramHash->{'filechoice'} = Apache::lonxml::get_all_text('/filechoice',
                   2923:                                                               $parser);
                   2924: }
                   2925: 
                   2926: sub end_filechoice { return ''; }
                   2927: 
                   2928: sub start_filefilter {
                   2929:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2930: 
                   2931:     if ($target ne 'helper') {
                   2932:         return '';
                   2933:     }
                   2934: 
                   2935:     my $contents = Apache::lonxml::get_all_text('/filefilter',
                   2936:                                                 $parser);
                   2937:     $contents = 'sub { my $filename = shift; ' . $contents . '}';
                   2938:     $paramHash->{FILTER_FUNC} = eval $contents;
                   2939: }
                   2940: 
                   2941: sub end_filefilter { return ''; }
1.3       bowersj2 2942: 
1.87      matthew  2943: { 
                   2944:     # used to generate unique id attributes for <input> tags. 
                   2945:     # internal use only.
                   2946:     my $id=0;
                   2947:     sub new_id { return $id++;}
                   2948: }
                   2949: 
1.3       bowersj2 2950: sub render {
                   2951:     my $self = shift;
1.5       bowersj2 2952:     my $result = '';
                   2953:     my $var = $self->{'variable'};
                   2954:     
                   2955:     my $subdirFunc = eval('sub {' . $self->{'filechoice'} . '}');
1.11      bowersj2 2956:     die 'Error in resource filter code for variable ' . 
                   2957:         {'variable'} . ', Perl said:' . $@ if $@;
                   2958: 
1.5       bowersj2 2959:     my $subdir = &$subdirFunc();
                   2960: 
                   2961:     my $filterFunc = $self->{FILTER_FUNC};
1.44      bowersj2 2962:     if (!defined($filterFunc)) {
                   2963: 	$filterFunc = &not_old_version;
                   2964:     }
1.5       bowersj2 2965:     my $buttons = '';
1.22      bowersj2 2966:     my $type = 'radio';
                   2967:     if ($self->{'multichoice'}) {
                   2968:         $type = 'checkbox';
                   2969:     }
1.5       bowersj2 2970: 
                   2971:     if ($self->{'multichoice'}) {
                   2972:         $result = <<SCRIPT;
1.112     albertel 2973: <script type="text/javascript">
                   2974: // <!--
1.18      bowersj2 2975:     function checkall(value, checkName) {
1.15      bowersj2 2976: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
                   2977:             ele = document.forms.helpform.elements[i];
1.157     raeburn  2978:             if (ele.name == checkName + '_forminput') {
1.15      bowersj2 2979:                 document.forms.helpform.elements[i].checked=value;
1.5       bowersj2 2980:             }
                   2981:         }
                   2982:     }
1.21      bowersj2 2983: 
1.22      bowersj2 2984:     function checkallclass(value, className) {
1.21      bowersj2 2985:         for (i=0; i<document.forms.helpform.elements.length; i++) {
                   2986:             ele = document.forms.helpform.elements[i];
1.22      bowersj2 2987:             if (ele.type == "$type" && ele.onclick) {
1.21      bowersj2 2988:                 document.forms.helpform.elements[i].checked=value;
                   2989:             }
                   2990:         }
                   2991:     }
1.112     albertel 2992: // -->
1.5       bowersj2 2993: </script>
                   2994: SCRIPT
1.68      sakharuk 2995:        my %lt=&Apache::lonlocal::texthash(
                   2996: 			'saf'  => "Select All Files",
                   2997: 		        'uaf'  => "Unselect All Files");
                   2998:        $buttons = <<BUTTONS;
1.5       bowersj2 2999: <br /> &nbsp;
1.68      sakharuk 3000: <input type="button" onclick="checkall(true, '$var')" value="$lt{'saf'}" />
                   3001: <input type="button" onclick="checkall(false, '$var')" value="$lt{'uaf'}" />
1.23      bowersj2 3002: BUTTONS
                   3003: 
1.69      sakharuk 3004:        %lt=&Apache::lonlocal::texthash(
1.68      sakharuk 3005: 			'sap'  => "Select All Published",
                   3006: 		        'uap'  => "Unselect All Published");
1.23      bowersj2 3007:         if ($helper->{VARS}->{'construction'}) {
1.68      sakharuk 3008:        $buttons .= <<BUTTONS;
                   3009: <input type="button" onclick="checkallclass(true, 'Published')" value="$lt{'sap'}" />
                   3010: <input type="button" onclick="checkallclass(false, 'Published')" value="$lt{'uap'}" />
1.5       bowersj2 3011: <br /> &nbsp;
                   3012: BUTTONS
1.23      bowersj2 3013:        }
1.5       bowersj2 3014:     }
                   3015: 
                   3016:     # Get the list of files in this directory.
1.183     raeburn  3017:     my (@fileList,$listref,$listerror);
1.5       bowersj2 3018: 
                   3019:     # If the subdirectory is in local CSTR space
1.47      albertel 3020:     my $metadir;
1.185     raeburn  3021:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.186     www      3022:     if ($subdir =~ m{^(?:\Q$londocroot\E)*/priv/[^/]+/[^/]+/(.*)$}) {
1.184     www      3023:         my $innerpath=$1;
1.186     www      3024:         unless ($subdir=~m{^\Q$londocroot\E}) {
                   3025:            $subdir=$londocroot.$subdir;
                   3026:         }
1.110     albertel 3027: 	my ($user,$domain)= 
1.189     raeburn  3028: 	    &Apache::lonnet::constructaccess($subdir);
1.184     www      3029: 	$metadir='/res/'.$domain.'/'.$user.'/'.$innerpath;
1.183     raeburn  3030:         ($listref,$listerror) =
                   3031:             &Apache::lonnet::dirlist($subdir,$domain,$user,undef,undef,'/');
1.5       bowersj2 3032:     } else {
                   3033:         # local library server resource space
1.183     raeburn  3034:         ($listref,$listerror) = 
                   3035:             &Apache::lonnet::dirlist($subdir,$env{'user.domain'},$env{'user.name'},undef,undef,'/');
1.5       bowersj2 3036:     }
1.3       bowersj2 3037: 
1.44      bowersj2 3038:     # Sort the fileList into order
1.183     raeburn  3039:     if (ref($listref) eq 'ARRAY') {
                   3040:         @fileList = sort {lc($a) cmp lc($b)} @{$listref};
                   3041:     }
1.44      bowersj2 3042: 
1.5       bowersj2 3043:     $result .= $buttons;
                   3044: 
1.6       bowersj2 3045:     if (defined $self->{ERROR_MSG}) {
                   3046:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
                   3047:     }
                   3048: 
1.20      bowersj2 3049:     $result .= '<table border="0" cellpadding="2" cellspacing="0">';
1.5       bowersj2 3050: 
                   3051:     # Keeps track if there are no choices, prints appropriate error
                   3052:     # if there are none. 
                   3053:     my $choices = 0;
                   3054:     # Print each legitimate file choice.
                   3055:     for my $file (@fileList) {
                   3056:         $file = (split(/&/, $file))[0];
                   3057:         if ($file eq '.' || $file eq '..') {
                   3058:             next;
                   3059:         }
                   3060:         my $fileName = $subdir .'/'. $file;
                   3061:         if (&$filterFunc($file)) {
1.24      sakharuk 3062: 	    my $status;
                   3063: 	    my $color;
                   3064: 	    if ($helper->{VARS}->{'construction'}) {
                   3065: 		($status, $color) = @{fileState($subdir, $file)};
                   3066: 	    } else {
                   3067: 		$status = '';
                   3068: 		$color = '';
                   3069: 	    }
1.22      bowersj2 3070: 
1.32      bowersj2 3071:             # Get the title
1.47      albertel 3072:             my $title = Apache::lonpubdir::getTitleString(($metadir?$metadir:$subdir) .'/'. $file);
1.32      bowersj2 3073: 
1.22      bowersj2 3074:             # Netscape 4 is stupid and there's nowhere to put the
                   3075:             # information on the input tag that the file is Published,
                   3076:             # Unpublished, etc. In *real* browsers we can just say
                   3077:             # "class='Published'" and check the className attribute of
                   3078:             # the input tag, but Netscape 4 is too stupid to understand
                   3079:             # that attribute, and un-comprehended attributes are not
                   3080:             # reflected into the object model. So instead, what I do 
                   3081:             # is either have or don't have an "onclick" handler that 
                   3082:             # does nothing, give Published files the onclick handler, and
                   3083:             # have the checker scripts check for that. Stupid and clumsy,
                   3084:             # and only gives us binary "yes/no" information (at least I
                   3085:             # couldn't figure out how to reach into the event handler's
                   3086:             # actual code to retreive a value), but it works well enough
                   3087:             # here.
1.23      bowersj2 3088:         
1.22      bowersj2 3089:             my $onclick = '';
1.23      bowersj2 3090:             if ($status eq 'Published' && $helper->{VARS}->{'construction'}) {
1.22      bowersj2 3091:                 $onclick = 'onclick="a=1" ';
                   3092:             }
1.87      matthew  3093:             my $id = &new_id();
1.20      bowersj2 3094:             $result .= '<tr><td align="right"' . " bgcolor='$color'>" .
1.22      bowersj2 3095:                 "<input $onclick type='$type' name='" . $var
1.157     raeburn  3096:             . "_forminput' ".qq{id="$id"}." value='" . HTML::Entities::encode($fileName,"<>&\"'").
1.5       bowersj2 3097:                 "'";
                   3098:             if (!$self->{'multichoice'} && $choices == 0) {
1.111     albertel 3099:                 $result .= ' checked="checked"';
1.5       bowersj2 3100:             }
1.87      matthew  3101:             $result .= "/></td><td bgcolor='$color'>".
                   3102:                 qq{<label for="$id">}. $file . "</label></td>" .
1.32      bowersj2 3103:                 "<td bgcolor='$color'>$title</td>" .
                   3104:                 "<td bgcolor='$color'>$status</td>" . "</tr>\n";
1.5       bowersj2 3105:             $choices++;
                   3106:         }
                   3107:     }
                   3108: 
                   3109:     $result .= "</table>\n";
                   3110: 
                   3111:     if (!$choices) {
1.47      albertel 3112:         $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 3113:     }
                   3114: 
                   3115:     $result .= $buttons;
                   3116: 
                   3117:     return $result;
1.20      bowersj2 3118: }
                   3119: 
                   3120: # Determine the state of the file: Published, unpublished, modified.
                   3121: # Return the color it should be in and a label as a two-element array
                   3122: # reference.
                   3123: # Logic lifted from lonpubdir.pm, even though I don't know that it's still
                   3124: # the most right thing to do.
                   3125: 
                   3126: sub fileState {
                   3127:     my $constructionSpaceDir = shift;
                   3128:     my $file = shift;
                   3129:     
1.100     albertel 3130:     my ($uname,$udom)=($env{'user.name'},$env{'user.domain'});
                   3131:     if ($env{'request.role'}=~/^ca\./) {
                   3132: 	(undef,$udom,$uname)=split(/\//,$env{'request.role'});
1.86      albertel 3133:     }
1.20      bowersj2 3134:     my $docroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   3135:     my $subdirpart = $constructionSpaceDir;
1.185     raeburn  3136:     $subdirpart =~ s{^\Q$docroot/priv/$udom/$uname\E}{};
1.86      albertel 3137:     my $resdir = $docroot . '/res/' . $udom . '/' . $uname .
1.20      bowersj2 3138:         $subdirpart;
                   3139: 
                   3140:     my @constructionSpaceFileStat = stat($constructionSpaceDir . '/' . $file);
                   3141:     my @resourceSpaceFileStat = stat($resdir . '/' . $file);
                   3142:     if (!@resourceSpaceFileStat) {
                   3143:         return ['Unpublished', '#FFCCCC'];
                   3144:     }
                   3145: 
                   3146:     my $constructionSpaceFileModified = $constructionSpaceFileStat[9];
                   3147:     my $resourceSpaceFileModified = $resourceSpaceFileStat[9];
                   3148:     
                   3149:     if ($constructionSpaceFileModified > $resourceSpaceFileModified) {
                   3150:         return ['Modified', '#FFFFCC'];
                   3151:     }
                   3152:     return ['Published', '#CCFFCC'];
1.4       bowersj2 3153: }
1.5       bowersj2 3154: 
1.4       bowersj2 3155: sub postprocess {
                   3156:     my $self = shift;
1.157     raeburn  3157:     my $result = $env{'form.' . $self->{'variable'} . '_forminput'};
1.6       bowersj2 3158:     if (!$result) {
                   3159:         $self->{ERROR_MSG} = 'You must choose at least one file '.
                   3160:             'to continue.';
                   3161:         return 0;
                   3162:     }
                   3163: 
1.5       bowersj2 3164:     if (defined($self->{NEXTSTATE})) {
                   3165:         $helper->changeState($self->{NEXTSTATE});
1.3       bowersj2 3166:     }
1.6       bowersj2 3167: 
                   3168:     return 1;
1.3       bowersj2 3169: }
1.8       bowersj2 3170: 
                   3171: 1;
                   3172: 
1.11      bowersj2 3173: package Apache::lonhelper::section;
                   3174: 
                   3175: =pod
                   3176: 
1.44      bowersj2 3177: =head2 Element: sectionX<section, helper element>
1.11      bowersj2 3178: 
                   3179: <section> allows the user to choose one or more sections from the current
                   3180: course.
                   3181: 
1.134     albertel 3182: It takes the standard attributes "variable", "multichoice",
                   3183: "allowempty" and "nextstate", meaning what they do for most other
                   3184: elements.
                   3185: 
                   3186: also takes a boolean 'onlysections' whcih will restrict this to only
                   3187: have sections and not include groups
1.11      bowersj2 3188: 
                   3189: =cut
                   3190: 
                   3191: no strict;
                   3192: @ISA = ("Apache::lonhelper::choices");
                   3193: use strict;
                   3194: 
                   3195: BEGIN {
                   3196:     &Apache::lonhelper::register('Apache::lonhelper::section',
                   3197:                                  ('section'));
                   3198: }
                   3199: 
                   3200: sub new {
                   3201:     my $ref = Apache::lonhelper::choices->new();
                   3202:     bless($ref);
                   3203: }
                   3204: 
                   3205: sub start_section {
                   3206:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3207: 
                   3208:     if ($target ne 'helper') {
                   3209:         return '';
                   3210:     }
1.12      bowersj2 3211: 
                   3212:     $paramHash->{CHOICES} = [];
                   3213: 
1.11      bowersj2 3214:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   3215:     $helper->declareVar($paramHash->{'variable'});
                   3216:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.133     albertel 3217:     $paramHash->{'allowempty'} = $token->[2]{'allowempty'};
1.11      bowersj2 3218:     if (defined($token->[2]{'nextstate'})) {
1.12      bowersj2 3219:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
1.11      bowersj2 3220:     }
                   3221: 
                   3222:     # Populate the CHOICES element
                   3223:     my %choices;
1.195     raeburn  3224:     my $usersec = $Apache::lonnet::env{'request.course.sec'};
1.11      bowersj2 3225: 
1.195     raeburn  3226:     if ($usersec ne '') {
                   3227:         $choices{$usersec} = $usersec;
                   3228:     } else {
                   3229:         my $section = Apache::loncoursedata::CL_SECTION();
                   3230:         my $classlist = Apache::loncoursedata::get_classlist();
                   3231:         foreach my $user (keys(%$classlist)) {
                   3232:             my $section_name = $classlist->{$user}[$section];
                   3233:             if (!$section_name) {
                   3234:                 $choices{"No section assigned"} = "";
                   3235:             } else {
                   3236:                 $choices{$section_name} = $section_name;
                   3237:             }
                   3238:         }
                   3239:  
                   3240:         if (exists($choices{"No section assigned"})) {
                   3241: 	    push(@{$paramHash->{CHOICES}}, 
                   3242: 	         ['No section assigned','No section assigned']);
                   3243: 	    delete($choices{"No section assigned"});
1.11      bowersj2 3244:         }
1.143     albertel 3245:     }
                   3246:     for my $section_name (sort {lc($a) cmp lc($b) } (keys(%choices))) {
                   3247: 	push @{$paramHash->{CHOICES}}, [$section_name, $section_name];
1.134     albertel 3248:     }
                   3249:     return if ($token->[2]{'onlysections'});
                   3250: 
                   3251:     # add in groups to the end of the list
1.151     raeburn  3252:     my %curr_groups = &Apache::longroup::coursegroups();
1.142     albertel 3253:     foreach my $group_name (sort(keys(%curr_groups))) {
                   3254: 	push(@{$paramHash->{CHOICES}}, [$group_name, $group_name]);
1.11      bowersj2 3255:     }
                   3256: }    
                   3257: 
1.12      bowersj2 3258: sub end_section {
                   3259:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.11      bowersj2 3260: 
1.12      bowersj2 3261:     if ($target ne 'helper') {
                   3262:         return '';
                   3263:     }
                   3264:     Apache::lonhelper::section->new();
                   3265: }    
1.11      bowersj2 3266: 1;
                   3267: 
1.128     raeburn  3268: package Apache::lonhelper::group;
                   3269: 
                   3270: =pod
                   3271:  
                   3272: =head2 Element: groupX<group, helper element>
                   3273:  
1.134     albertel 3274: <group> allows the user to choose one or more groups from the current course.
                   3275: 
                   3276: It takes the standard attributes "variable", "multichoice",
                   3277:  "allowempty" and "nextstate", meaning what they do for most other
                   3278:  elements.
1.128     raeburn  3279: 
                   3280: =cut
                   3281: 
                   3282: no strict;
                   3283: @ISA = ("Apache::lonhelper::choices");
                   3284: use strict;
                   3285: 
                   3286: BEGIN {
                   3287:     &Apache::lonhelper::register('Apache::lonhelper::group',
                   3288:                                  ('group'));
                   3289: }
                   3290: 
                   3291: sub new {
                   3292:     my $ref = Apache::lonhelper::choices->new();
                   3293:     bless($ref);
                   3294: }
                   3295:  
                   3296: sub start_group {
                   3297:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3298:  
                   3299:     if ($target ne 'helper') {
                   3300:         return '';
                   3301:     }
                   3302: 
                   3303:     $paramHash->{CHOICES} = [];
                   3304: 
                   3305:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   3306:     $helper->declareVar($paramHash->{'variable'});
                   3307:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
1.133     albertel 3308:     $paramHash->{'allowempty'} = $token->[2]{'allowempty'};
1.128     raeburn  3309:     if (defined($token->[2]{'nextstate'})) {
                   3310:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
                   3311:     }
                   3312: 
                   3313:     # Populate the CHOICES element
                   3314:     my %choices;
                   3315: 
1.151     raeburn  3316:     my %curr_groups = &Apache::longroup::coursegroups();
1.143     albertel 3317:     foreach my $group_name (sort {lc($a) cmp lc($b)} (keys(%curr_groups))) {
1.142     albertel 3318: 	push(@{$paramHash->{CHOICES}}, [$group_name, $group_name]);
1.128     raeburn  3319:     }
                   3320: }
1.134     albertel 3321: 
1.128     raeburn  3322: sub end_group {
                   3323:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3324: 
                   3325:     if ($target ne 'helper') {
                   3326:         return '';
                   3327:     }
                   3328:     Apache::lonhelper::group->new();
                   3329: }
                   3330: 1;
                   3331: 
1.34      bowersj2 3332: package Apache::lonhelper::string;
                   3333: 
                   3334: =pod
                   3335: 
1.44      bowersj2 3336: =head2 Element: stringX<string, helper element>
1.34      bowersj2 3337: 
                   3338: string elements provide a string entry field for the user. string elements
                   3339: take the usual 'variable' and 'nextstate' parameters. string elements
                   3340: also pass through 'maxlength' and 'size' attributes to the input tag.
1.180     foxr     3341: Since you could have multiple strings in a helper state, each with its own
                   3342: validator, all but the last string should have
                   3343: noproceed='1' so that _all_ validators are evaluated before the next
                   3344: state can be reached.
1.34      bowersj2 3345: 
                   3346: string honors the defaultvalue tag, if given.
                   3347: 
1.38      bowersj2 3348: string honors the validation function, if given.
                   3349: 
1.34      bowersj2 3350: =cut
                   3351: 
                   3352: no strict;
                   3353: @ISA = ("Apache::lonhelper::element");
                   3354: use strict;
1.76      sakharuk 3355: use Apache::lonlocal;
1.34      bowersj2 3356: 
                   3357: BEGIN {
                   3358:     &Apache::lonhelper::register('Apache::lonhelper::string',
                   3359:                               ('string'));
                   3360: }
                   3361: 
                   3362: sub new {
                   3363:     my $ref = Apache::lonhelper::element->new();
1.180     foxr     3364:     $ref->{'PROCEED'} = 1;      # By default postprocess goes to next state.
1.34      bowersj2 3365:     bless($ref);
                   3366: }
                   3367: 
                   3368: # CONSTRUCTION: Construct the message element from the XML
                   3369: sub start_string {
                   3370:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3371: 
                   3372:     if ($target ne 'helper') {
                   3373:         return '';
                   3374:     }
                   3375: 
                   3376:     $paramHash->{'variable'} = $token->[2]{'variable'};
                   3377:     $helper->declareVar($paramHash->{'variable'});
                   3378:     $paramHash->{'nextstate'} = $token->[2]{'nextstate'};
                   3379:     $paramHash->{'maxlength'} = $token->[2]{'maxlength'};
                   3380:     $paramHash->{'size'} = $token->[2]{'size'};
                   3381:     return '';
                   3382: }
                   3383: 
                   3384: sub end_string {
                   3385:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3386: 
1.180     foxr     3387: 
1.34      bowersj2 3388:     if ($target ne 'helper') {
                   3389:         return '';
                   3390:     }
1.180     foxr     3391:     my $state = Apache::lonhelper::string->new();
                   3392: 
                   3393: 
                   3394:     if(&Apache::lonxml::get_param('noproceed', $parstack, $safeeval, undef, 1)) {
                   3395: 	$state->noproceed();
                   3396:     }
                   3397: 
                   3398:    
                   3399: 
1.34      bowersj2 3400:     return '';
                   3401: }
                   3402: 
1.180     foxr     3403: sub noproceed() {
                   3404:     my $self = shift;
                   3405:     $self->{PROCEED}  = 0;
                   3406: }
                   3407: 
1.34      bowersj2 3408: sub render {
                   3409:     my $self = shift;
1.38      bowersj2 3410:     my $result = '';
                   3411: 
                   3412:     if (defined $self->{ERROR_MSG}) {
1.97      albertel 3413:         $result .= '<p><font color="#FF0000">' . $self->{ERROR_MSG} . '</font></p>';
1.38      bowersj2 3414:     }
                   3415: 
1.182     raeburn  3416:     $result .= '<input type="text" name="' . $self->{'variable'} . '_forminput"';
1.34      bowersj2 3417: 
                   3418:     if (defined($self->{'size'})) {
                   3419:         $result .= ' size="' . $self->{'size'} . '"';
                   3420:     }
                   3421:     if (defined($self->{'maxlength'})) {
                   3422:         $result .= ' maxlength="' . $self->{'maxlength'} . '"';
                   3423:     }
                   3424: 
                   3425:     if (defined($self->{DEFAULT_VALUE})) {
                   3426:         my $valueFunc = eval($self->{DEFAULT_VALUE});
                   3427:         die 'Error in default value code for variable ' . 
                   3428:             $self->{'variable'} . ', Perl said: ' . $@ if $@;
                   3429:         $result .= ' value="' . &$valueFunc($helper, $self) . '"';
                   3430:     }
                   3431: 
                   3432:     $result .= ' />';
                   3433: 
                   3434:     return $result;
                   3435: }
                   3436: 
                   3437: # If a NEXTSTATE was given, switch to it
                   3438: sub postprocess {
                   3439:     my $self = shift;
1.38      bowersj2 3440: 
                   3441:     if (defined($self->{VALIDATOR})) {
                   3442: 	my $validator = eval($self->{VALIDATOR});
1.138     albertel 3443: 	die 'Died during evaluation of validator code; Perl said: ' . $@ if $@;
1.38      bowersj2 3444: 	my $invalid = &$validator($helper, $state, $self, $self->getValue());
                   3445: 	if ($invalid) {
                   3446: 	    $self->{ERROR_MSG} = $invalid;
                   3447: 	    return 0;
                   3448: 	}
                   3449:     }
                   3450: 
1.180     foxr     3451:     if (defined($self->{'nextstate'}) && $self->{PROCEED}) {
1.38      bowersj2 3452:         $helper->changeState($self->{'nextstate'});
1.34      bowersj2 3453:     }
                   3454: 
                   3455:     return 1;
                   3456: }
                   3457: 
                   3458: 1;
                   3459: 
1.8       bowersj2 3460: package Apache::lonhelper::general;
                   3461: 
                   3462: =pod
                   3463: 
1.44      bowersj2 3464: =head2 General-purpose tag: <exec>X<exec, helper tag>
1.8       bowersj2 3465: 
1.44      bowersj2 3466: The contents of the exec tag are executed as Perl code, B<not> inside a 
1.100     albertel 3467: safe space, so the full range of $env and such is available. The code
1.8       bowersj2 3468: will be executed as a subroutine wrapped with the following code:
                   3469: 
                   3470: "sub { my $helper = shift; my $state = shift;" and
                   3471: 
                   3472: "}"
                   3473: 
                   3474: The return value is ignored.
                   3475: 
                   3476: $helper is the helper object. Feel free to add methods to the helper
                   3477: object to support whatever manipulation you may need to do (for instance,
                   3478: overriding the form location if the state is the final state; see 
1.44      bowersj2 3479: parameter.helper for an example).
1.8       bowersj2 3480: 
                   3481: $state is the $paramHash that has currently been generated and may
                   3482: be manipulated by the code in exec. Note that the $state is not yet
                   3483: an actual state B<object>, it is just a hash, so do not expect to
                   3484: be able to call methods on it.
                   3485: 
                   3486: =cut
                   3487: 
1.83      sakharuk 3488: use Apache::lonlocal;
1.102     albertel 3489: use Apache::lonnet;
1.83      sakharuk 3490: 
1.8       bowersj2 3491: BEGIN {
                   3492:     &Apache::lonhelper::register('Apache::lonhelper::general',
1.11      bowersj2 3493:                                  'exec', 'condition', 'clause',
                   3494:                                  'eval');
1.8       bowersj2 3495: }
                   3496: 
                   3497: sub start_exec {
                   3498:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3499: 
                   3500:     if ($target ne 'helper') {
                   3501:         return '';
                   3502:     }
                   3503:     
                   3504:     my $code = &Apache::lonxml::get_all_text('/exec', $parser);
                   3505:     
                   3506:     $code = eval ('sub { my $helper = shift; my $state = shift; ' .
                   3507:         $code . "}");
1.11      bowersj2 3508:     die 'Error in <exec>, Perl said: '. $@ if $@;
1.8       bowersj2 3509:     &$code($helper, $paramHash);
                   3510: }
                   3511: 
                   3512: sub end_exec { return ''; }
                   3513: 
                   3514: =pod
                   3515: 
                   3516: =head2 General-purpose tag: <condition>
                   3517: 
                   3518: The <condition> tag allows you to mask out parts of the helper code
                   3519: depending on some programatically determined condition. The condition
                   3520: tag contains a tag <clause> which contains perl code that when wrapped
                   3521: with "sub { my $helper = shift; my $state = shift; " and "}", returns
                   3522: a true value if the XML in the condition should be evaluated as a normal
                   3523: part of the helper, or false if it should be completely discarded.
                   3524: 
                   3525: The <clause> tag must be the first sub-tag of the <condition> tag or
                   3526: it will not work as expected.
                   3527: 
                   3528: =cut
                   3529: 
                   3530: # The condition tag just functions as a marker, it doesn't have
                   3531: # to "do" anything. Technically it doesn't even have to be registered
                   3532: # with the lonxml code, but I leave this here to be explicit about it.
                   3533: sub start_condition { return ''; }
                   3534: sub end_condition { return ''; }
                   3535: 
                   3536: sub start_clause {
                   3537:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3538: 
                   3539:     if ($target ne 'helper') {
                   3540:         return '';
                   3541:     }
                   3542:     
                   3543:     my $clause = Apache::lonxml::get_all_text('/clause', $parser);
                   3544:     $clause = eval('sub { my $helper = shift; my $state = shift; '
                   3545:         . $clause . '}');
1.11      bowersj2 3546:     die 'Error in clause of condition, Perl said: ' . $@ if $@;
1.8       bowersj2 3547:     if (!&$clause($helper, $paramHash)) {
                   3548:         # Discard all text until the /condition.
1.155     albertel 3549: 	my $end_tag = $paramHash->{SKIPTAG} || '/condition';
                   3550:         &Apache::lonxml::get_all_text($end_tag, $parser);
1.8       bowersj2 3551:     }
                   3552: }
                   3553: 
                   3554: sub end_clause { return ''; }
1.11      bowersj2 3555: 
                   3556: =pod
                   3557: 
1.44      bowersj2 3558: =head2 General-purpose tag: <eval>X<eval, helper tag>
1.11      bowersj2 3559: 
                   3560: The <eval> tag will be evaluated as a subroutine call passed in the
                   3561: current helper object and state hash as described in <condition> above,
                   3562: but is expected to return a string to be printed directly to the
                   3563: screen. This is useful for dynamically generating messages. 
                   3564: 
                   3565: =cut
                   3566: 
                   3567: # This is basically a type of message.
                   3568: # Programmatically setting $paramHash->{NEXTSTATE} would work, though
                   3569: # it's probably bad form.
                   3570: 
                   3571: sub start_eval {
                   3572:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3573: 
                   3574:     if ($target ne 'helper') {
                   3575:         return '';
                   3576:     }
                   3577:     
                   3578:     my $program = Apache::lonxml::get_all_text('/eval', $parser);
                   3579:     $program = eval('sub { my $helper = shift; my $state = shift; '
                   3580:         . $program . '}');
                   3581:     die 'Error in eval code, Perl said: ' . $@ if $@;
                   3582:     $paramHash->{MESSAGE_TEXT} = &$program($helper, $paramHash);
                   3583: }
                   3584: 
                   3585: sub end_eval { 
                   3586:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3587: 
                   3588:     if ($target ne 'helper') {
                   3589:         return '';
                   3590:     }
                   3591: 
                   3592:     Apache::lonhelper::message->new();
                   3593: }
                   3594: 
1.13      bowersj2 3595: 1;
                   3596: 
1.27      bowersj2 3597: package Apache::lonhelper::final;
                   3598: 
                   3599: =pod
                   3600: 
1.44      bowersj2 3601: =head2 Element: finalX<final, helper tag>
1.27      bowersj2 3602: 
                   3603: <final> is a special element that works with helpers that use the <finalcode>
1.44      bowersj2 3604: tagX<finalcode, helper tag>. It goes through all the states and elements, executing the <finalcode>
1.27      bowersj2 3605: snippets and collecting the results. Finally, it takes the user out of the
                   3606: helper, going to a provided page.
                   3607: 
1.34      bowersj2 3608: If the parameter "restartCourse" is true, this will override the buttons and
1.176     bisitz   3609: will make a Save button (Finish Helper) that will re-initialize the course for them,
1.34      bowersj2 3610: which is useful for the Course Initialization helper so the users never see
                   3611: the old values taking effect.
                   3612: 
1.93      albertel 3613: If the parameter "restartCourse" is not true a 'Finish' Button will be
                   3614: presented that takes the user back to whatever was defined as <exitpage>
                   3615: 
1.27      bowersj2 3616: =cut
                   3617: 
                   3618: no strict;
                   3619: @ISA = ("Apache::lonhelper::element");
                   3620: use strict;
1.62      matthew  3621: use Apache::lonlocal;
1.100     albertel 3622: use Apache::lonnet;
1.27      bowersj2 3623: BEGIN {
                   3624:     &Apache::lonhelper::register('Apache::lonhelper::final',
                   3625:                                  ('final', 'exitpage'));
                   3626: }
                   3627: 
                   3628: sub new {
                   3629:     my $ref = Apache::lonhelper::element->new();
                   3630:     bless($ref);
                   3631: }
                   3632: 
1.34      bowersj2 3633: sub start_final { 
                   3634:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3635: 
                   3636:     if ($target ne 'helper') {
                   3637:         return '';
                   3638:     }
                   3639: 
                   3640:     $paramHash->{'restartCourse'} = $token->[2]{'restartCourse'};
                   3641: 
                   3642:     return ''; 
                   3643: }
1.27      bowersj2 3644: 
                   3645: sub end_final {
                   3646:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3647: 
                   3648:     if ($target ne 'helper') {
                   3649:         return '';
                   3650:     }
                   3651: 
                   3652:     Apache::lonhelper::final->new();
                   3653:    
                   3654:     return '';
                   3655: }
                   3656: 
                   3657: sub start_exitpage {
                   3658:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3659: 
                   3660:     if ($target ne 'helper') {
                   3661:         return '';
                   3662:     }
                   3663: 
                   3664:     $paramHash->{EXIT_PAGE} = &Apache::lonxml::get_all_text('/exitpage',
                   3665:                                                             $parser);
                   3666: 
                   3667:     return '';
                   3668: }
                   3669: 
                   3670: sub end_exitpage { return ''; }
                   3671: 
                   3672: sub render {
                   3673:     my $self = shift;
                   3674: 
                   3675:     my @results;
                   3676: 
                   3677:     # Collect all the results
1.193     raeburn  3678:     for my $stateName (keys(%{$helper->{STATES}})) {
1.27      bowersj2 3679:         my $state = $helper->{STATES}->{$stateName};
                   3680:         
                   3681:         for my $element (@{$state->{ELEMENTS}}) {
                   3682:             if (defined($element->{FINAL_CODE})) {
                   3683:                 # Compile the code.
1.31      bowersj2 3684:                 my $code = 'sub { my $helper = shift; my $element = shift; ' 
                   3685:                     . $element->{FINAL_CODE} . '}';
1.27      bowersj2 3686:                 $code = eval($code);
                   3687:                 die 'Error while executing final code for element with var ' .
                   3688:                     $element->{'variable'} . ', Perl said: ' . $@ if $@;
                   3689: 
1.31      bowersj2 3690:                 my $result = &$code($helper, $element);
1.27      bowersj2 3691:                 if ($result) {
                   3692:                     push @results, $result;
                   3693:                 }
                   3694:             }
                   3695:         }
                   3696:     }
                   3697: 
1.40      bowersj2 3698:     my $result;
1.27      bowersj2 3699: 
1.40      bowersj2 3700:     if (scalar(@results) != 0) {
                   3701: 	$result .= "<ul>\n";
                   3702: 	for my $re (@results) {
                   3703: 	    $result .= '    <li>' . $re . "</li>\n";
                   3704: 	}
                   3705: 	
                   3706: 	if (!@results) {
1.59      bowersj2 3707: 	    $result .= '    <li>' . 
                   3708: 		&mt('No changes were made to current settings.') . '</li>';
1.40      bowersj2 3709: 	}
                   3710: 	
                   3711: 	$result .= '</ul>';
1.34      bowersj2 3712:     }
                   3713: 
1.93      albertel 3714:     my $actionURL = $self->{EXIT_PAGE};
                   3715:     my $targetURL = '';
1.176     bisitz   3716: 	my $finish=&mt('Save');
1.34      bowersj2 3717:     if ($self->{'restartCourse'}) {
1.103     albertel 3718: 	$actionURL = '/adm/roles';
1.93      albertel 3719: 	$targetURL = '/adm/menu';
1.100     albertel 3720: 	if ($env{'course.'.$env{'request.course.id'}.'.url'}=~/^uploaded/) {
1.64      albertel 3721: 	    $targetURL = '/adm/coursedocs';
                   3722: 	} else {
                   3723: 	    $targetURL = '/adm/navmaps';
                   3724: 	}
1.100     albertel 3725: 	if ($env{'course.'.$env{'request.course.id'}.'.clonedfrom'}) {
1.45      bowersj2 3726: 	    $targetURL = '/adm/parmset?overview=1';
                   3727: 	}
1.34      bowersj2 3728:     }
1.170     schafran 3729:     my $previous = HTML::Entities::encode(&mt("Back"), '<>&"');
                   3730:     my $next = HTML::Entities::encode(&mt("Next"), '<>&"');
1.176     bisitz   3731:     $result .= "<p>\n" .
1.179     droeschl 3732: 	"<form action='".$actionURL."' method='post' >\n" .
1.93      albertel 3733: 	"<input type='button' onclick='history.go(-1)' value='$previous' />" .
                   3734: 	"<input type='hidden' name='orgurl' value='$targetURL' />" .
                   3735: 	"<input type='hidden' name='selectrole' value='1' />\n" .
1.100     albertel 3736: 	"<input type='hidden' name='" . $env{'request.role'} . 
1.93      albertel 3737: 	"' value='1' />\n<input type='submit' value='" . $finish . "' />\n" .
1.176     bisitz   3738: 	"</form></p>\n";
1.34      bowersj2 3739: 
1.40      bowersj2 3740:     return $result;
1.34      bowersj2 3741: }
                   3742: 
                   3743: sub overrideForm {
1.93      albertel 3744:     return 1;
1.27      bowersj2 3745: }
                   3746: 
                   3747: 1;
                   3748: 
1.13      bowersj2 3749: package Apache::lonhelper::parmwizfinal;
                   3750: 
1.160     albertel 3751: # This is the final state for the parm helper. It is not generally useful,
1.13      bowersj2 3752: # so it is not perldoc'ed. It does its own processing.
                   3753: # It is represented with <parmwizfinal />, and
                   3754: # should later be moved to lonparmset.pm .
                   3755: 
                   3756: no strict;
                   3757: @ISA = ('Apache::lonhelper::element');
                   3758: use strict;
1.69      sakharuk 3759: use Apache::lonlocal;
1.102     albertel 3760: use Apache::lonnet;
1.11      bowersj2 3761: 
1.13      bowersj2 3762: BEGIN {
                   3763:     &Apache::lonhelper::register('Apache::lonhelper::parmwizfinal',
                   3764:                                  ('parmwizfinal'));
                   3765: }
                   3766: 
                   3767: use Time::localtime;
                   3768: 
                   3769: sub new {
                   3770:     my $ref = Apache::lonhelper::choices->new();
                   3771:     bless ($ref);
                   3772: }
                   3773: 
                   3774: sub start_parmwizfinal { return ''; }
                   3775: 
                   3776: sub end_parmwizfinal {
                   3777:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   3778: 
                   3779:     if ($target ne 'helper') {
                   3780:         return '';
                   3781:     }
                   3782:     Apache::lonhelper::parmwizfinal->new();
                   3783: }
                   3784: 
                   3785: # Renders a form that, when submitted, will form the input to lonparmset.pm
                   3786: sub render {
                   3787:     my $self = shift;
                   3788:     my $vars = $helper->{VARS};
                   3789: 
                   3790:     # FIXME: Unify my designators with the standard ones
1.48      bowersj2 3791:     my %dateTypeHash = ('open_date' => "opening date",
                   3792:                         'due_date' => "due date",
                   3793:                         'answer_date' => "answer date",
                   3794: 			'tries' => 'number of tries',
                   3795: 			'weight' => 'problem weight'
1.38      bowersj2 3796: 			);
1.13      bowersj2 3797:     my %parmTypeHash = ('open_date' => "0_opendate",
                   3798:                         'due_date' => "0_duedate",
1.38      bowersj2 3799:                         'answer_date' => "0_answerdate",
1.48      bowersj2 3800: 			'tries' => '0_maxtries',
                   3801: 			'weight' => '0_weight' );
1.107     albertel 3802:     my %realParmName = ('open_date' => "opendate",
                   3803:                         'due_date' => "duedate",
                   3804:                         'answer_date' => "answerdate",
                   3805: 			'tries' => 'maxtries',
                   3806: 			'weight' => 'weight' );
1.13      bowersj2 3807:     
                   3808:     my $affectedResourceId = "";
                   3809:     my $parm_name = $parmTypeHash{$vars->{ACTION_TYPE}};
                   3810:     my $level = "";
1.27      bowersj2 3811:     my $resourceString;
                   3812:     my $symb;
                   3813:     my $paramlevel;
1.95      albertel 3814:     
1.13      bowersj2 3815:     # Print the granularity, depending on the action
                   3816:     if ($vars->{GRANULARITY} eq 'whole_course') {
1.167     bisitz   3817:         $resourceString .= '<li>'.&mt('for [_1]all resources in the course[_2]','<b>','</b>').'</li>';
1.104     albertel 3818: 	if ($vars->{TARGETS} eq 'course') {
1.150     albertel 3819: 	    $level = 14; # general course, see lonparmset.pm perldoc
1.104     albertel 3820: 	} elsif ($vars->{TARGETS} eq 'section') {
1.150     albertel 3821: 	    $level = 9;
                   3822: 	} elsif ($vars->{TARGETS} eq 'group') {
1.104     albertel 3823: 	    $level = 6;
                   3824: 	} else {
                   3825: 	    $level = 3;
                   3826: 	}
1.13      bowersj2 3827:         $affectedResourceId = "0.0";
1.27      bowersj2 3828:         $symb = 'a';
                   3829:         $paramlevel = 'general';
1.13      bowersj2 3830:     } elsif ($vars->{GRANULARITY} eq 'map') {
1.41      bowersj2 3831:         my $navmap = Apache::lonnavmaps::navmap->new();
1.169     raeburn  3832:         if (defined($navmap)) {
                   3833:              my $res = $navmap->getByMapPc($vars->{RESOURCE_ID});
                   3834:              my $title = $res->compTitle();
                   3835:              $symb = $res->symb();
                   3836:              $resourceString .= '<li>'.&mt('for the map named [_1]',"<b>$title</b>").'</li>';
                   3837:         } else {
                   3838:             $resourceString .= '<li>'.&mt('for the map ID [_1] (name unavailable)','<b>'.$vars->{RESOURCE_ID}.'</b>').'</li>';
                   3839:             &Apache::lonnet::logthis('Retrieval of map title failed in lonhelper.pm - could not create navmap object for course.');
                   3840: 
                   3841:         }
1.104     albertel 3842: 	if ($vars->{TARGETS} eq 'course') {
1.150     albertel 3843: 	    $level = 13; # general course, see lonparmset.pm perldoc
1.104     albertel 3844: 	} elsif ($vars->{TARGETS} eq 'section') {
1.150     albertel 3845: 	    $level = 8;
                   3846: 	} elsif ($vars->{TARGETS} eq 'group') {
1.104     albertel 3847: 	    $level = 5;
                   3848: 	} else {
                   3849: 	    $level = 2;
                   3850: 	}
1.13      bowersj2 3851:         $affectedResourceId = $vars->{RESOURCE_ID};
1.27      bowersj2 3852:         $paramlevel = 'map';
1.13      bowersj2 3853:     } else {
1.95      albertel 3854:         my $part = $vars->{RESOURCE_ID_part};
                   3855: 	if ($part ne 'All Parts' && $part) { $parm_name=~s/^0/$part/; } else { $part=&mt('All Parts'); }
1.169     raeburn  3856:         my $navmap = Apache::lonnavmaps::navmap->new();
                   3857:         if (defined($navmap)) {
                   3858:             my $res = $navmap->getById($vars->{RESOURCE_ID});
                   3859:             $symb = $res->symb();
                   3860:             my $title = $res->compTitle();
1.176     bisitz   3861:             $resourceString .= '<li>'.&mt('for the resource named [_1], part [_2]',"<b>$title</b>","<b>$part</b>").'</li>';
1.169     raeburn  3862:         } else {
1.176     bisitz   3863:             $resourceString .= '<li>'.&mt('for the resource ID [_1] (name unavailable), part [_2]','<b>'.$vars->{RESOURCE_ID}.'</b>',"<b>$part</b>").'</li>';
1.169     raeburn  3864:             &Apache::lonnet::logthis('Retrieval of resource title failed in lonhelper.pm - could not create navmap object for course.');
                   3865:         }
1.104     albertel 3866: 	if ($vars->{TARGETS} eq 'course') {
1.150     albertel 3867: 	    $level = 10; # general course, see lonparmset.pm perldoc
1.104     albertel 3868: 	} elsif ($vars->{TARGETS} eq 'section') {
1.150     albertel 3869: 	    $level = 7;
                   3870: 	} elsif ($vars->{TARGETS} eq 'group') {
1.104     albertel 3871: 	    $level = 4;
                   3872: 	} else {
                   3873: 	    $level = 1;
                   3874: 	}
1.13      bowersj2 3875:         $affectedResourceId = $vars->{RESOURCE_ID};
1.27      bowersj2 3876:         $paramlevel = 'full';
1.13      bowersj2 3877:     }
                   3878: 
1.172     bisitz   3879:     my $result = "<form name='helpform' method='post' action='/adm/parmset#$affectedResourceId&$parm_name&$level'>\n";
1.104     albertel 3880:     $result .= "<input type='hidden' name='action' value='settable' />\n";
                   3881:     $result .= "<input type='hidden' name='dis' value='helper' />\n";
1.107     albertel 3882:     $result .= "<input type='hidden' name='pscat' value='".
                   3883: 	$realParmName{$vars->{ACTION_TYPE}}."' />\n";
1.95      albertel 3884:     if ($vars->{GRANULARITY} eq 'resource') {
                   3885: 	$result .= "<input type='hidden' name='symb' value='".
                   3886: 	    HTML::Entities::encode($symb,"'<>&\"") . "' />\n";
1.108     albertel 3887:     } elsif ($vars->{GRANULARITY} eq 'map') {
                   3888: 	$result .= "<input type='hidden' name='pschp' value='".
                   3889: 	    $affectedResourceId."' />\n";
1.95      albertel 3890:     }
1.104     albertel 3891:     my $part = $vars->{RESOURCE_ID_part};
                   3892:     if ($part eq 'All Parts' || !$part) { $part=0; }
                   3893:     $result .= "<input type='hidden' name='psprt' value='".
                   3894: 	HTML::Entities::encode($part,"'<>&\"") . "' />\n";
                   3895: 
1.176     bisitz   3896:     $result .= '<p class="LC_info">'
                   3897:               .&mt('Confirm that this information is correct, then click &quot;Save&quot; to complete setting the parameter.')
                   3898:               .'</p>'
                   3899:               .'<ul>';
1.27      bowersj2 3900:     
                   3901:     # Print the type of manipulation:
1.73      albertel 3902:     my $extra;
1.38      bowersj2 3903:     if ($vars->{ACTION_TYPE} eq 'tries') {
1.73      albertel 3904: 	$extra =  $vars->{TRIES};
1.38      bowersj2 3905:     }
1.48      bowersj2 3906:     if ($vars->{ACTION_TYPE} eq 'weight') {
1.73      albertel 3907: 	$extra =  $vars->{WEIGHT};
                   3908:     }
                   3909:     $result .= "<li>";
1.74      matthew  3910:     my $what = &mt($dateTypeHash{$vars->{ACTION_TYPE}});
1.73      albertel 3911:     if ($extra) {
                   3912: 	$result .= &mt('Setting the [_1] to [_2]',"<b>$what</b>",$extra);
                   3913:     } else {
                   3914: 	$result .= &mt('Setting the [_1]',"<b>$what</b>");
1.48      bowersj2 3915:     }
1.38      bowersj2 3916:     $result .= "</li>\n";
1.27      bowersj2 3917:     if ($vars->{ACTION_TYPE} eq 'due_date' || 
                   3918:         $vars->{ACTION_TYPE} eq 'answer_date') {
                   3919:         # for due dates, we default to "date end" type entries
                   3920:         $result .= "<input type='hidden' name='recent_date_end' " .
                   3921:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   3922:         $result .= "<input type='hidden' name='pres_value' " . 
                   3923:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   3924:         $result .= "<input type='hidden' name='pres_type' " .
                   3925:             "value='date_end' />\n";
                   3926:     } elsif ($vars->{ACTION_TYPE} eq 'open_date') {
                   3927:         $result .= "<input type='hidden' name='recent_date_start' ".
                   3928:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   3929:         $result .= "<input type='hidden' name='pres_value' " .
                   3930:             "value='" . $vars->{PARM_DATE} . "' />\n";
                   3931:         $result .= "<input type='hidden' name='pres_type' " .
                   3932:             "value='date_start' />\n";
1.38      bowersj2 3933:     } elsif ($vars->{ACTION_TYPE} eq 'tries') {
                   3934: 	$result .= "<input type='hidden' name='pres_value' " .
                   3935: 	    "value='" . $vars->{TRIES} . "' />\n";
1.104     albertel 3936:         $result .= "<input type='hidden' name='pres_type' " .
                   3937:             "value='int_pos' />\n";
1.48      bowersj2 3938:     } elsif ($vars->{ACTION_TYPE} eq 'weight') {
                   3939: 	$result .= "<input type='hidden' name='pres_value' " .
                   3940: 	    "value='" . $vars->{WEIGHT} . "' />\n";
1.38      bowersj2 3941:     }
1.27      bowersj2 3942: 
                   3943:     $result .= $resourceString;
                   3944:     
1.13      bowersj2 3945:     # Print targets
                   3946:     if ($vars->{TARGETS} eq 'course') {
1.167     bisitz   3947:         $result .= '<li>'.&mt('for [_1]all students in course[_2]','<b>','</b>').'</li>';
1.13      bowersj2 3948:     } elsif ($vars->{TARGETS} eq 'section') {
                   3949:         my $section = $vars->{SECTION_NAME};
1.79      sakharuk 3950:         $result .= '<li>'.&mt('for section [_1]',"<b>$section</b>").'</li>';
1.104     albertel 3951: 	$result .= "<input type='hidden' name='csec' value='" .
1.89      foxr     3952:             HTML::Entities::encode($section,"'<>&\"") . "' />\n";
1.128     raeburn  3953:     } elsif ($vars->{TARGETS} eq 'group') {
                   3954:         my $group = $vars->{GROUP_NAME};
                   3955:         $result .= '<li>'.&mt('for group [_1]',"<b>$group</b>").'</li>';
                   3956:         $result .= "<input type='hidden' name='cgroup' value='" .
                   3957:             HTML::Entities::encode($group,"'<>&\"") . "' />\n";
1.13      bowersj2 3958:     } else {
                   3959:         # FIXME: This is probably wasteful! Store the name!
                   3960:         my $classlist = Apache::loncoursedata::get_classlist();
1.109     albertel 3961: 	my ($uname,$udom)=split(':',$vars->{USER_NAME});
1.106     albertel 3962:         my $name = $classlist->{$uname.':'.$udom}->[6];
1.79      sakharuk 3963:         $result .= '<li>'.&mt('for [_1]',"<b>$name</b>").'</li>';
1.13      bowersj2 3964:         $result .= "<input type='hidden' name='uname' value='".
1.89      foxr     3965:             HTML::Entities::encode($uname,"'<>&\"") . "' />\n";
1.13      bowersj2 3966:         $result .= "<input type='hidden' name='udom' value='".
1.89      foxr     3967:             HTML::Entities::encode($udom,"'<>&\"") . "' />\n";
1.13      bowersj2 3968:     }
                   3969: 
                   3970:     # Print value
1.48      bowersj2 3971:     if ($vars->{ACTION_TYPE} ne 'tries' && $vars->{ACTION_TYPE} ne 'weight') {
1.166     raeburn  3972:         my $showdate = &Apache::lonlocal::locallocaltime($vars->{PARM_DATE});
                   3973: 	$result .= '<li>'.&mt('to [_1] ([_2])',"<b>".$showdate."</b>",Apache::lonnavmaps::timeToHumanString($vars->{PARM_DATE}))."</li>\n";
1.38      bowersj2 3974:     }
1.176     bisitz   3975: 
                   3976: 	$result .= '</ul>';
1.38      bowersj2 3977:  
1.176     bisitz   3978: # FIXME: Make previous button working
                   3979: #        Found to be dysfunctional when used to change the selected student
                   3980: #   my $previous = HTML::Entities::encode(&mt("Back"), '<>&"');
                   3981:     my $buttons .= '<p><span class="LC_nobreak">'
                   3982: #                 .'<input name="back" type="button"'
                   3983: #                 .' value="'.$previous.'" onclick="history.go(-1)" />'
                   3984:                   .' <input type="submit" value="'.&mt('Save').'" />' # Finish Helper
                   3985:                   .'</span></p>'."\n";
                   3986: 
1.13      bowersj2 3987:     # print pres_marker
                   3988:     $result .= "\n<input type='hidden' name='pres_marker'" .
                   3989:         " value='$affectedResourceId&$parm_name&$level' />\n";
1.27      bowersj2 3990:     
                   3991:     # Make the table appear
                   3992:     $result .= "\n<input type='hidden' value='true' name='prevvisit' />";
                   3993:     $result .= "\n<input type='hidden' value='$symb' name='pssymb' />";
                   3994:     $result .= "\n<input type='hidden' value='$paramlevel' name='parmlev' />";
1.13      bowersj2 3995: 
1.176     bisitz   3996:     $result .= $buttons;
1.13      bowersj2 3997: 
                   3998:     return $result;
                   3999: }
                   4000:     
                   4001: sub overrideForm {
                   4002:     return 1;
                   4003: }
1.5       bowersj2 4004: 
1.4       bowersj2 4005: 1;
1.3       bowersj2 4006: 
1.1       bowersj2 4007: __END__
1.3       bowersj2 4008: 

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