File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.47: download - view: text, annotated - select for diffs
Thu Sep 25 20:39:32 2003 UTC (20 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- better search for metadata when directory in CSTR
- understand ~ CSTR space directories

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

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