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

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

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