File:  [LON-CAPA] / loncom / interface / lonhelper.pm
Revision 1.48: download - view: text, annotated - select for diffs
Mon Sep 29 16:33:09 2003 UTC (20 years, 7 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Docs updates, new features for resources, and now, support changing
weights in the parameter helper.

    1: # The LearningOnline Network with CAPA
    2: # .helper XML handler to implement the LON-CAPA helper
    3: #
    4: # $Id: lonhelper.pm,v 1.48 2003/09/29 16:33:09 bowersj2 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 Elements
  930: 
  931: =head2 Element: messageX<message, helper element>
  932: 
  933: Message elements display their contents, and
  934: transition directly to the state in the <nextstate> attribute. Example:
  935: 
  936:  <message nextstate='GET_NAME'>
  937:    This is the <b>message</b> the user will see, 
  938:                  <i>HTML allowed</i>.
  939:    </message>
  940: 
  941: This will display the HTML message and transition to the 'nextstate' if
  942: given. The HTML will be directly inserted into the helper, so if you don't
  943: want text to run together, you'll need to manually wrap the message text
  944: in <p> tags, or whatever is appropriate for your HTML.
  945: 
  946: Message tags do not add in whitespace, so if you want it, you'll need to add
  947: it into states. This is done so you can inline some elements, such as 
  948: the <date> element, right between two messages, giving the appearence that 
  949: the <date> element appears inline. (Note the elements can not be embedded
  950: within each other.)
  951: 
  952: This is also a good template for creating your own new states, as it has
  953: very little code beyond the state template.
  954: 
  955: =cut
  956: 
  957: no strict;
  958: @ISA = ("Apache::lonhelper::element");
  959: use strict;
  960: 
  961: BEGIN {
  962:     &Apache::lonhelper::register('Apache::lonhelper::message',
  963:                               ('message'));
  964: }
  965: 
  966: sub new {
  967:     my $ref = Apache::lonhelper::element->new();
  968:     bless($ref);
  969: }
  970: 
  971: # CONSTRUCTION: Construct the message element from the XML
  972: sub start_message {
  973:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  974: 
  975:     if ($target ne 'helper') {
  976:         return '';
  977:     }
  978: 
  979:     $paramHash->{MESSAGE_TEXT} = &Apache::lonxml::get_all_text('/message',
  980:                                                                $parser);
  981: 
  982:     if (defined($token->[2]{'nextstate'})) {
  983:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
  984:     }
  985:     return '';
  986: }
  987: 
  988: sub end_message {
  989:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  990: 
  991:     if ($target ne 'helper') {
  992:         return '';
  993:     }
  994:     Apache::lonhelper::message->new();
  995:     return '';
  996: }
  997: 
  998: sub render {
  999:     my $self = shift;
 1000: 
 1001:     return $self->{MESSAGE_TEXT};
 1002: }
 1003: # If a NEXTSTATE was given, switch to it
 1004: sub postprocess {
 1005:     my $self = shift;
 1006:     if (defined($self->{NEXTSTATE})) {
 1007:         $helper->changeState($self->{NEXTSTATE});
 1008:     }
 1009: 
 1010:     return 1;
 1011: }
 1012: 1;
 1013: 
 1014: package Apache::lonhelper::choices;
 1015: 
 1016: =pod
 1017: 
 1018: =head2 Element: choicesX<choices, helper element>
 1019: 
 1020: Choice states provide a single choice to the user as a text selection box.
 1021: A "choice" is two pieces of text, one which will be displayed to the user
 1022: (the "human" value), and one which will be passed back to the program
 1023: (the "computer" value). For instance, a human may choose from a list of
 1024: resources on disk by title, while your program wants the file name.
 1025: 
 1026: <choices> takes an attribute "variable" to control which helper variable
 1027: the result is stored in.
 1028: 
 1029: <choices> takes an attribute "multichoice" which, if set to a true
 1030: value, will allow the user to select multiple choices.
 1031: 
 1032: <choices> takes an attribute "allowempty" which, if set to a true 
 1033: value, will allow the user to select none of the choices without raising
 1034: an error message.
 1035: 
 1036: =head3 SUB-TAGS
 1037: 
 1038: <choices> can have the following subtags:X<choice, helper tag>
 1039: 
 1040: =over 4
 1041: 
 1042: =item * <nextstate>state_name</nextstate>: If given, this will cause the
 1043:       choice element to transition to the given state after executing.
 1044:       This will override the <nextstate> passed to <choices> (if any).
 1045: 
 1046: =item * <choice />: If the choices are static,
 1047:       this element will allow you to specify them. Each choice
 1048:       contains  attribute, "computer", as described above. The
 1049:       content of the tag will be used as the human label.
 1050:       For example,  
 1051:       <choice computer='234-12-7312'>Bobby McDormik</choice>.
 1052: 
 1053: <choice> can take a parameter "eval", which if set to
 1054: a true value, will cause the contents of the tag to be
 1055: evaluated as it would be in an <eval> tag; see <eval> tag
 1056: below.
 1057: 
 1058: <choice> may optionally contain a 'nextstate' attribute, which
 1059: will be the state transistioned to if the choice is made, if
 1060: the choice is not multichoice. This will override the nextstate
 1061: passed to the parent C<choices> tag.
 1062: 
 1063: =back
 1064: 
 1065: To create the choices programmatically, either wrap the choices in 
 1066: <condition> tags (prefered), or use an <exec> block inside the <choice>
 1067: tag. Store the choices in $state->{CHOICES}, which is a list of list
 1068: references, where each list has three strings. The first is the human
 1069: name, the second is the computer name. and the third is the option
 1070: next state. For example:
 1071: 
 1072:  <exec>
 1073:     for (my $i = 65; $i < 65 + 26; $i++) {
 1074:         push @{$state->{CHOICES}}, [chr($i), $i, 'next'];
 1075:     }
 1076:  </exec>
 1077: 
 1078: This will allow the user to select from the letters A-Z (in ASCII), while
 1079: passing the ASCII value back into the helper variables, and the state
 1080: will in all cases transition to 'next'.
 1081: 
 1082: You can mix and match methods of creating choices, as long as you always 
 1083: "push" onto the choice list, rather then wiping it out. (You can even 
 1084: remove choices programmatically, but that would probably be bad form.)
 1085: 
 1086: =head3 defaultvalue support
 1087: 
 1088: Choices supports default values both in multichoice and single choice mode.
 1089: In single choice mode, have the defaultvalue tag's function return the 
 1090: computer value of the box you want checked. If the function returns a value
 1091: that does not correspond to any of the choices, the default behavior of selecting
 1092: the first choice will be preserved.
 1093: 
 1094: For multichoice, return a string with the computer values you want checked,
 1095: delimited by triple pipes. Note this matches how the result of the <choices>
 1096: tag is stored in the {VARS} hash.
 1097: 
 1098: =cut
 1099: 
 1100: no strict;
 1101: @ISA = ("Apache::lonhelper::element");
 1102: use strict;
 1103: 
 1104: BEGIN {
 1105:     &Apache::lonhelper::register('Apache::lonhelper::choices',
 1106:                               ('choice', 'choices'));
 1107: }
 1108: 
 1109: sub new {
 1110:     my $ref = Apache::lonhelper::element->new();
 1111:     bless($ref);
 1112: }
 1113: 
 1114: # CONSTRUCTION: Construct the message element from the XML
 1115: sub start_choices {
 1116:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1117: 
 1118:     if ($target ne 'helper') {
 1119:         return '';
 1120:     }
 1121: 
 1122:     # Need to initialize the choices list, so everything can assume it exists
 1123:     $paramHash->{'variable'} = $token->[2]{'variable'} if (!defined($paramHash->{'variable'}));
 1124:     $helper->declareVar($paramHash->{'variable'});
 1125:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 1126:     $paramHash->{'allowempty'} = $token->[2]{'allowempty'};
 1127:     $paramHash->{CHOICES} = [];
 1128:     return '';
 1129: }
 1130: 
 1131: sub end_choices {
 1132:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1133: 
 1134:     if ($target ne 'helper') {
 1135:         return '';
 1136:     }
 1137:     Apache::lonhelper::choices->new();
 1138:     return '';
 1139: }
 1140: 
 1141: sub start_choice {
 1142:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1143: 
 1144:     if ($target ne 'helper') {
 1145:         return '';
 1146:     }
 1147: 
 1148:     my $computer = $token->[2]{'computer'};
 1149:     my $human = &Apache::lonxml::get_all_text('/choice',
 1150:                                               $parser);
 1151:     my $nextstate = $token->[2]{'nextstate'};
 1152:     my $evalFlag = $token->[2]{'eval'};
 1153:     push @{$paramHash->{CHOICES}}, [$human, $computer, $nextstate, 
 1154:                                     $evalFlag];
 1155:     return '';
 1156: }
 1157: 
 1158: sub end_choice {
 1159:     return '';
 1160: }
 1161: 
 1162: sub render {
 1163:     my $self = shift;
 1164:     my $var = $self->{'variable'};
 1165:     my $buttons = '';
 1166:     my $result = '';
 1167: 
 1168:     if ($self->{'multichoice'}) {
 1169:         $result .= <<SCRIPT;
 1170: <script>
 1171:     function checkall(value, checkName) {
 1172: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
 1173:             ele = document.forms.helpform.elements[i];
 1174:             if (ele.name == checkName + '.forminput') {
 1175:                 document.forms.helpform.elements[i].checked=value;
 1176:             }
 1177:         }
 1178:     }
 1179: </script>
 1180: SCRIPT
 1181:     }
 1182: 
 1183:     # Only print "select all" and "unselect all" if there are five or
 1184:     # more choices; fewer then that and it looks silly.
 1185:     if ($self->{'multichoice'} && scalar(@{$self->{CHOICES}}) > 4) {
 1186:         $buttons = <<BUTTONS;
 1187: <br />
 1188: <input type="button" onclick="checkall(true, '$var')" value="Select All" />
 1189: <input type="button" onclick="checkall(false, '$var')" value="Unselect All" />
 1190: <br />&nbsp;
 1191: BUTTONS
 1192:     }
 1193: 
 1194:     if (defined $self->{ERROR_MSG}) {
 1195:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br />';
 1196:     }
 1197: 
 1198:     $result .= $buttons;
 1199:     
 1200:     $result .= "<table>\n\n";
 1201: 
 1202:     my %checkedChoices;
 1203:     my $checkedChoicesFunc;
 1204: 
 1205:     if (defined($self->{DEFAULT_VALUE})) {
 1206:         $checkedChoicesFunc = eval ($self->{DEFAULT_VALUE});
 1207:         die 'Error in default value code for variable ' . 
 1208:             $self->{'variable'} . ', Perl said: ' . $@ if $@;
 1209:     } else {
 1210:         $checkedChoicesFunc = sub { return ''; };
 1211:     }
 1212: 
 1213:     # Process which choices should be checked.
 1214:     if ($self->{'multichoice'}) {
 1215:         for my $selectedChoice (split(/\|\|\|/, (&$checkedChoicesFunc($helper, $self)))) {
 1216:             $checkedChoices{$selectedChoice} = 1;
 1217:         }
 1218:     } else {
 1219:         # single choice
 1220:         my $selectedChoice = &$checkedChoicesFunc($helper, $self);
 1221:         
 1222:         my $foundChoice = 0;
 1223:         
 1224:         # check that the choice is in the list of choices.
 1225:         for my $choice (@{$self->{CHOICES}}) {
 1226:             if ($choice->[1] eq $selectedChoice) {
 1227:                 $checkedChoices{$choice->[1]} = 1;
 1228:                 $foundChoice = 1;
 1229:             }
 1230:         }
 1231:         
 1232:         # If we couldn't find the choice, pick the first one 
 1233:         if (!$foundChoice) {
 1234:             $checkedChoices{$self->{CHOICES}->[0]->[1]} = 1;
 1235:         }
 1236:     }
 1237: 
 1238:     my $type = "radio";
 1239:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
 1240:     foreach my $choice (@{$self->{CHOICES}}) {
 1241:         $result .= "<tr>\n<td width='20'>&nbsp;</td>\n";
 1242:         $result .= "<td valign='top'><input type='$type' name='$var.forminput'"
 1243:             . "' value='" . 
 1244:             HTML::Entities::encode($choice->[1]) 
 1245:             . "'";
 1246:         if ($checkedChoices{$choice->[1]}) {
 1247:             $result .= " checked ";
 1248:         }
 1249:         my $choiceLabel = $choice->[0];
 1250:         if ($choice->[4]) {  # if we need to evaluate this choice
 1251:             $choiceLabel = "sub { my $helper = shift; my $state = shift;" .
 1252:                 $choiceLabel . "}";
 1253:             $choiceLabel = eval($choiceLabel);
 1254:             $choiceLabel = &$choiceLabel($helper, $self);
 1255:         }
 1256:         $result .= "/></td><td> " . $choiceLabel . "</td></tr>\n";
 1257:     }
 1258:     $result .= "</table>\n\n\n";
 1259:     $result .= $buttons;
 1260: 
 1261:     return $result;
 1262: }
 1263: 
 1264: # If a NEXTSTATE was given or a nextstate for this choice was
 1265: # given, switch to it
 1266: sub postprocess {
 1267:     my $self = shift;
 1268:     my $chosenValue = $ENV{'form.' . $self->{'variable'} . '.forminput'};
 1269: 
 1270:     if (!defined($chosenValue) && !$self->{'allowempty'}) {
 1271:         $self->{ERROR_MSG} = "You must choose one or more choices to" .
 1272:             " continue.";
 1273:         return 0;
 1274:     }
 1275: 
 1276:     if (ref($chosenValue)) {
 1277:         $helper->{VARS}->{$self->{'variable'}} = join('|||', @$chosenValue);
 1278:     }
 1279: 
 1280:     if (defined($self->{NEXTSTATE})) {
 1281:         $helper->changeState($self->{NEXTSTATE});
 1282:     }
 1283:     
 1284:     foreach my $choice (@{$self->{CHOICES}}) {
 1285:         if ($choice->[1] eq $chosenValue) {
 1286:             if (defined($choice->[2])) {
 1287:                 $helper->changeState($choice->[2]);
 1288:             }
 1289:         }
 1290:     }
 1291:     return 1;
 1292: }
 1293: 1;
 1294: 
 1295: package Apache::lonhelper::dropdown;
 1296: 
 1297: =pod
 1298: 
 1299: =head2 Element: dropdownX<dropdown, helper tag>
 1300: 
 1301: A drop-down provides a drop-down box instead of a radio button
 1302: box. Because most people do not know how to use a multi-select
 1303: drop-down box, that option is not allowed. Otherwise, the arguments
 1304: are the same as "choices", except "allowempty" is also meaningless.
 1305: 
 1306: <dropdown> takes an attribute "variable" to control which helper variable
 1307: the result is stored in.
 1308: 
 1309: =head3 SUB-TAGS
 1310: 
 1311: <choice>, which acts just as it does in the "choices" element.
 1312: 
 1313: =cut
 1314: 
 1315: no strict;
 1316: @ISA = ("Apache::lonhelper::element");
 1317: use strict;
 1318: 
 1319: BEGIN {
 1320:     &Apache::lonhelper::register('Apache::lonhelper::dropdown',
 1321:                               ('dropdown'));
 1322: }
 1323: 
 1324: sub new {
 1325:     my $ref = Apache::lonhelper::element->new();
 1326:     bless($ref);
 1327: }
 1328: 
 1329: # CONSTRUCTION: Construct the message element from the XML
 1330: sub start_dropdown {
 1331:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1332: 
 1333:     if ($target ne 'helper') {
 1334:         return '';
 1335:     }
 1336: 
 1337:     # Need to initialize the choices list, so everything can assume it exists
 1338:     $paramHash->{'variable'} = $token->[2]{'variable'} if (!defined($paramHash->{'variable'}));
 1339:     $helper->declareVar($paramHash->{'variable'});
 1340:     $paramHash->{CHOICES} = [];
 1341:     return '';
 1342: }
 1343: 
 1344: sub end_dropdown {
 1345:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1346: 
 1347:     if ($target ne 'helper') {
 1348:         return '';
 1349:     }
 1350:     Apache::lonhelper::dropdown->new();
 1351:     return '';
 1352: }
 1353: 
 1354: sub render {
 1355:     my $self = shift;
 1356:     my $var = $self->{'variable'};
 1357:     my $result = '';
 1358: 
 1359:     if (defined $self->{ERROR_MSG}) {
 1360:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br />';
 1361:     }
 1362: 
 1363:     my %checkedChoices;
 1364:     my $checkedChoicesFunc;
 1365: 
 1366:     if (defined($self->{DEFAULT_VALUE})) {
 1367:         $checkedChoicesFunc = eval ($self->{DEFAULT_VALUE});
 1368:         die 'Error in default value code for variable ' . 
 1369:             $self->{'variable'} . ', Perl said: ' . $@ if $@;
 1370:     } else {
 1371:         $checkedChoicesFunc = sub { return ''; };
 1372:     }
 1373: 
 1374:     # single choice
 1375:     my $selectedChoice = &$checkedChoicesFunc($helper, $self);
 1376:     
 1377:     my $foundChoice = 0;
 1378:     
 1379:     # check that the choice is in the list of choices.
 1380:     for my $choice (@{$self->{CHOICES}}) {
 1381: 	if ($choice->[1] eq $selectedChoice) {
 1382: 	    $checkedChoices{$choice->[1]} = 1;
 1383: 	    $foundChoice = 1;
 1384: 	}
 1385:     }
 1386:     
 1387:     # If we couldn't find the choice, pick the first one 
 1388:     if (!$foundChoice) {
 1389: 	$checkedChoices{$self->{CHOICES}->[0]->[1]} = 1;
 1390:     }
 1391: 
 1392:     $result .= "<select name='${var}.forminput'>\n";
 1393:     foreach my $choice (@{$self->{CHOICES}}) {
 1394:         $result .= "<option value='" . 
 1395:             HTML::Entities::encode($choice->[1]) 
 1396:             . "'";
 1397:         if ($checkedChoices{$choice->[1]}) {
 1398:             $result .= " selected";
 1399:         }
 1400:         my $choiceLabel = $choice->[0];
 1401:         if ($choice->[4]) {  # if we need to evaluate this choice
 1402:             $choiceLabel = "sub { my $helper = shift; my $state = shift;" .
 1403:                 $choiceLabel . "}";
 1404:             $choiceLabel = eval($choiceLabel);
 1405:             $choiceLabel = &$choiceLabel($helper, $self);
 1406:         }
 1407:         $result .= ">" . $choiceLabel . "\n";
 1408:     }
 1409:     $result .= "</select>\n";
 1410: 
 1411:     return $result;
 1412: }
 1413: 
 1414: # If a NEXTSTATE was given or a nextstate for this choice was
 1415: # given, switch to it
 1416: sub postprocess {
 1417:     my $self = shift;
 1418:     my $chosenValue = $ENV{'form.' . $self->{'variable'} . '.forminput'};
 1419: 
 1420:     if (!defined($chosenValue) && !$self->{'allowempty'}) {
 1421:         $self->{ERROR_MSG} = "You must choose one or more choices to" .
 1422:             " continue.";
 1423:         return 0;
 1424:     }
 1425: 
 1426:     if (defined($self->{NEXTSTATE})) {
 1427:         $helper->changeState($self->{NEXTSTATE});
 1428:     }
 1429:     
 1430:     foreach my $choice (@{$self->{CHOICES}}) {
 1431:         if ($choice->[1] eq $chosenValue) {
 1432:             if (defined($choice->[2])) {
 1433:                 $helper->changeState($choice->[2]);
 1434:             }
 1435:         }
 1436:     }
 1437:     return 1;
 1438: }
 1439: 1;
 1440: 
 1441: package Apache::lonhelper::date;
 1442: 
 1443: =pod
 1444: 
 1445: =head2 Element: dateX<date, helper element>
 1446: 
 1447: Date elements allow the selection of a date with a drop down list.
 1448: 
 1449: Date elements can take two attributes:
 1450: 
 1451: =over 4
 1452: 
 1453: =item * B<variable>: The name of the variable to store the chosen
 1454:         date in. Required.
 1455: 
 1456: =item * B<hoursminutes>: If a true value, the date will show hours
 1457:         and minutes, as well as month/day/year. If false or missing,
 1458:         the date will only show the month, day, and year.
 1459: 
 1460: =back
 1461: 
 1462: Date elements contain only an option <nextstate> tag to determine
 1463: the next state.
 1464: 
 1465: Example:
 1466: 
 1467:  <date variable="DUE_DATE" hoursminutes="1">
 1468:    <nextstate>choose_why</nextstate>
 1469:    </date>
 1470: 
 1471: =cut
 1472: 
 1473: no strict;
 1474: @ISA = ("Apache::lonhelper::element");
 1475: use strict;
 1476: 
 1477: use Time::localtime;
 1478: 
 1479: BEGIN {
 1480:     &Apache::lonhelper::register('Apache::lonhelper::date',
 1481:                               ('date'));
 1482: }
 1483: 
 1484: # Don't need to override the "new" from element
 1485: sub new {
 1486:     my $ref = Apache::lonhelper::element->new();
 1487:     bless($ref);
 1488: }
 1489: 
 1490: my @months = ("January", "February", "March", "April", "May", "June", "July",
 1491: 	      "August", "September", "October", "November", "December");
 1492: 
 1493: # CONSTRUCTION: Construct the message element from the XML
 1494: sub start_date {
 1495:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1496: 
 1497:     if ($target ne 'helper') {
 1498:         return '';
 1499:     }
 1500: 
 1501:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1502:     $helper->declareVar($paramHash->{'variable'});
 1503:     $paramHash->{'hoursminutes'} = $token->[2]{'hoursminutes'};
 1504: }
 1505: 
 1506: sub end_date {
 1507:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1508: 
 1509:     if ($target ne 'helper') {
 1510:         return '';
 1511:     }
 1512:     Apache::lonhelper::date->new();
 1513:     return '';
 1514: }
 1515: 
 1516: sub render {
 1517:     my $self = shift;
 1518:     my $result = "";
 1519:     my $var = $self->{'variable'};
 1520: 
 1521:     my $date;
 1522:     
 1523:     # Default date: The current hour.
 1524:     $date = localtime();
 1525:     $date->min(0);
 1526: 
 1527:     if (defined $self->{ERROR_MSG}) {
 1528:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 1529:     }
 1530: 
 1531:     # Month
 1532:     my $i;
 1533:     $result .= "<select name='${var}month'>\n";
 1534:     for ($i = 0; $i < 12; $i++) {
 1535:         if ($i == $date->mon) {
 1536:             $result .= "<option value='$i' selected>";
 1537:         } else {
 1538:             $result .= "<option value='$i'>";
 1539:         }
 1540:         $result .= $months[$i] . "</option>\n";
 1541:     }
 1542:     $result .= "</select>\n";
 1543: 
 1544:     # Day
 1545:     $result .= "<select name='${var}day'>\n";
 1546:     for ($i = 1; $i < 32; $i++) {
 1547:         if ($i == $date->mday) {
 1548:             $result .= '<option selected>';
 1549:         } else {
 1550:             $result .= '<option>';
 1551:         }
 1552:         $result .= "$i</option>\n";
 1553:     }
 1554:     $result .= "</select>,\n";
 1555: 
 1556:     # Year
 1557:     $result .= "<select name='${var}year'>\n";
 1558:     for ($i = 2000; $i < 2030; $i++) { # update this after 64-bit dates
 1559:         if ($date->year + 1900 == $i) {
 1560:             $result .= "<option selected>";
 1561:         } else {
 1562:             $result .= "<option>";
 1563:         }
 1564:         $result .= "$i</option>\n";
 1565:     }
 1566:     $result .= "</select>,\n";
 1567: 
 1568:     # Display Hours and Minutes if they are called for
 1569:     if ($self->{'hoursminutes'}) {
 1570:         # Build hour
 1571:         $result .= "<select name='${var}hour'>\n";
 1572:         $result .= "<option " . ($date->hour == 0 ? 'selected ':'') .
 1573:             " value='0'>midnight</option>\n";
 1574:         for ($i = 1; $i < 12; $i++) {
 1575:             if ($date->hour == $i) {
 1576:                 $result .= "<option selected value='$i'>$i a.m.</option>\n";
 1577:             } else {
 1578:                 $result .= "<option value='$i'>$i a.m</option>\n";
 1579:             }
 1580:         }
 1581:         $result .= "<option " . ($date->hour == 12 ? 'selected ':'') .
 1582:             " value='12'>noon</option>\n";
 1583:         for ($i = 13; $i < 24; $i++) {
 1584:             my $printedHour = $i - 12;
 1585:             if ($date->hour == $i) {
 1586:                 $result .= "<option selected value='$i'>$printedHour p.m.</option>\n";
 1587:             } else {
 1588:                 $result .= "<option value='$i'>$printedHour p.m.</option>\n";
 1589:             }
 1590:         }
 1591: 
 1592:         $result .= "</select> :\n";
 1593: 
 1594:         $result .= "<select name='${var}minute'>\n";
 1595:         for ($i = 0; $i < 60; $i++) {
 1596:             my $printedMinute = $i;
 1597:             if ($i < 10) {
 1598:                 $printedMinute = "0" . $printedMinute;
 1599:             }
 1600:             if ($date->min == $i) {
 1601:                 $result .= "<option selected>";
 1602:             } else {
 1603:                 $result .= "<option>";
 1604:             }
 1605:             $result .= "$printedMinute</option>\n";
 1606:         }
 1607:         $result .= "</select>\n";
 1608:     }
 1609: 
 1610:     return $result;
 1611: 
 1612: }
 1613: # If a NEXTSTATE was given, switch to it
 1614: sub postprocess {
 1615:     my $self = shift;
 1616:     my $var = $self->{'variable'};
 1617:     my $month = $ENV{'form.' . $var . 'month'}; 
 1618:     my $day = $ENV{'form.' . $var . 'day'}; 
 1619:     my $year = $ENV{'form.' . $var . 'year'}; 
 1620:     my $min = 0; 
 1621:     my $hour = 0;
 1622:     if ($self->{'hoursminutes'}) {
 1623:         $min = $ENV{'form.' . $var . 'minute'};
 1624:         $hour = $ENV{'form.' . $var . 'hour'};
 1625:     }
 1626: 
 1627:     my $chosenDate = Time::Local::timelocal(0, $min, $hour, $day, $month, $year);
 1628:     # Check to make sure that the date was not automatically co-erced into a 
 1629:     # valid date, as we want to flag that as an error
 1630:     # This happens for "Feb. 31", for instance, which is coerced to March 2 or
 1631:     # 3, depending on if it's a leapyear
 1632:     my $checkDate = localtime($chosenDate);
 1633: 
 1634:     if ($checkDate->mon != $month || $checkDate->mday != $day ||
 1635:         $checkDate->year + 1900 != $year) {
 1636:         $self->{ERROR_MSG} = "Can't use " . $months[$month] . " $day, $year as a "
 1637:             . "date because it doesn't exist. Please enter a valid date.";
 1638:         return 0;
 1639:     }
 1640: 
 1641:     $helper->{VARS}->{$var} = $chosenDate;
 1642: 
 1643:     if (defined($self->{NEXTSTATE})) {
 1644:         $helper->changeState($self->{NEXTSTATE});
 1645:     }
 1646: 
 1647:     return 1;
 1648: }
 1649: 1;
 1650: 
 1651: package Apache::lonhelper::resource;
 1652: 
 1653: =pod
 1654: 
 1655: =head2 Element: resourceX<resource, helper element>
 1656: 
 1657: <resource> elements allow the user to select one or multiple resources
 1658: from the current course. You can filter out which resources they can view,
 1659: and filter out which resources they can select. The course will always
 1660: be displayed fully expanded, because of the difficulty of maintaining
 1661: selections across folder openings and closings. If this is fixed, then
 1662: the user can manipulate the folders.
 1663: 
 1664: <resource> takes the standard variable attribute to control what helper
 1665: variable stores the results. It also takes a "multichoice"X<multichoice> attribute,
 1666: which controls whether the user can select more then one resource. The 
 1667: "toponly" attribute controls whether the resource display shows just the
 1668: resources in that sequence, or recurses into all sub-sequences, defaulting
 1669: to false. The "suppressEmptySequences" attribute reflects the 
 1670: suppressEmptySequences argument to the render routine, which will cause
 1671: folders that have all of their contained resources filtered out to also
 1672: be filtered out. The 'addstatus' attribute, if true, will add the icon
 1673: and long status display columns to the display.
 1674: 
 1675: =head3 SUB-TAGS
 1676: 
 1677: =over 4
 1678: 
 1679: =item * <filterfunc>X<filterfunc>: If you want to filter what resources are displayed
 1680:   to the user, use a filter func. The <filterfunc> tag should contain
 1681:   Perl code that when wrapped with "sub { my $res = shift; " and "}" is 
 1682:   a function that returns true if the resource should be displayed, 
 1683:   and false if it should be skipped. $res is a resource object. 
 1684:   (See Apache::lonnavmaps documentation for information about the 
 1685:   resource object.)
 1686: 
 1687: =item * <choicefunc>X<choicefunc>: Same as <filterfunc>, except that controls whether
 1688:   the given resource can be chosen. (It is almost always a good idea to
 1689:   show the user the folders, for instance, but you do not always want to 
 1690:   let the user select them.)
 1691: 
 1692: =item * <nextstate>: Standard nextstate behavior.
 1693: 
 1694: =item * <valuefunc>X<valuefunc>: This function controls what is returned by the resource
 1695:   when the user selects it. Like filterfunc and choicefunc, it should be
 1696:   a function fragment that when wrapped by "sub { my $res = shift; " and
 1697:   "}" returns a string representing what you want to have as the value. By
 1698:   default, the value will be the resource ID of the object ($res->{ID}).
 1699: 
 1700: =item * <mapurl>X<mapurl>: If the URL of a map is given here, only that map
 1701:   will be displayed, instead of the whole course. If the attribute
 1702:   "evaluate" is given and is true, the contents of the mapurl will be
 1703:   evaluated with "sub { my $helper = shift; my $state = shift;" and
 1704:   "}", with the return value used as the mapurl.
 1705: 
 1706: =back
 1707: 
 1708: =cut
 1709: 
 1710: no strict;
 1711: @ISA = ("Apache::lonhelper::element");
 1712: use strict;
 1713: 
 1714: BEGIN {
 1715:     &Apache::lonhelper::register('Apache::lonhelper::resource',
 1716:                               ('resource', 'filterfunc', 
 1717:                                'choicefunc', 'valuefunc',
 1718:                                'mapurl'));
 1719: }
 1720: 
 1721: sub new {
 1722:     my $ref = Apache::lonhelper::element->new();
 1723:     bless($ref);
 1724: }
 1725: 
 1726: # CONSTRUCTION: Construct the message element from the XML
 1727: sub start_resource {
 1728:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1729: 
 1730:     if ($target ne 'helper') {
 1731:         return '';
 1732:     }
 1733: 
 1734:     $paramHash->{'variable'} = $token->[2]{'variable'};
 1735:     $helper->declareVar($paramHash->{'variable'});
 1736:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 1737:     $paramHash->{'suppressEmptySequences'} = $token->[2]{'suppressEmptySequences'};
 1738:     $paramHash->{'toponly'} = $token->[2]{'toponly'};
 1739:     $paramHash->{'addstatus'} = $token->[2]{'addstatus'};
 1740:     return '';
 1741: }
 1742: 
 1743: sub end_resource {
 1744:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1745: 
 1746:     if ($target ne 'helper') {
 1747:         return '';
 1748:     }
 1749:     if (!defined($paramHash->{FILTER_FUNC})) {
 1750:         $paramHash->{FILTER_FUNC} = sub {return 1;};
 1751:     }
 1752:     if (!defined($paramHash->{CHOICE_FUNC})) {
 1753:         $paramHash->{CHOICE_FUNC} = sub {return 1;};
 1754:     }
 1755:     if (!defined($paramHash->{VALUE_FUNC})) {
 1756:         $paramHash->{VALUE_FUNC} = sub {my $res = shift; return $res->{ID}; };
 1757:     }
 1758:     Apache::lonhelper::resource->new();
 1759:     return '';
 1760: }
 1761: 
 1762: sub start_filterfunc {
 1763:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1764: 
 1765:     if ($target ne 'helper') {
 1766:         return '';
 1767:     }
 1768: 
 1769:     my $contents = Apache::lonxml::get_all_text('/filterfunc',
 1770:                                                 $parser);
 1771:     $contents = 'sub { my $res = shift; ' . $contents . '}';
 1772:     $paramHash->{FILTER_FUNC} = eval $contents;
 1773: }
 1774: 
 1775: sub end_filterfunc { return ''; }
 1776: 
 1777: sub start_choicefunc {
 1778:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1779: 
 1780:     if ($target ne 'helper') {
 1781:         return '';
 1782:     }
 1783: 
 1784:     my $contents = Apache::lonxml::get_all_text('/choicefunc',
 1785:                                                 $parser);
 1786:     $contents = 'sub { my $res = shift; ' . $contents . '}';
 1787:     $paramHash->{CHOICE_FUNC} = eval $contents;
 1788: }
 1789: 
 1790: sub end_choicefunc { return ''; }
 1791: 
 1792: sub start_valuefunc {
 1793:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1794: 
 1795:     if ($target ne 'helper') {
 1796:         return '';
 1797:     }
 1798: 
 1799:     my $contents = Apache::lonxml::get_all_text('/valuefunc',
 1800:                                                 $parser);
 1801:     $contents = 'sub { my $res = shift; ' . $contents . '}';
 1802:     $paramHash->{VALUE_FUNC} = eval $contents;
 1803: }
 1804: 
 1805: sub end_valuefunc { return ''; }
 1806: 
 1807: sub start_mapurl {
 1808:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1809: 
 1810:     if ($target ne 'helper') {
 1811:         return '';
 1812:     }
 1813: 
 1814:     my $contents = Apache::lonxml::get_all_text('/mapurl',
 1815:                                                 $parser);
 1816:     $paramHash->{EVAL_MAP_URL} = $token->[2]{'evaluate'};
 1817:     $paramHash->{MAP_URL} = $contents;
 1818: }
 1819: 
 1820: sub end_mapurl { return ''; }
 1821: 
 1822: # A note, in case I don't get to this before I leave.
 1823: # If someone complains about the "Back" button returning them
 1824: # to the previous folder state, instead of returning them to
 1825: # the previous helper state, the *correct* answer is for the helper
 1826: # to keep track of how many times the user has manipulated the folders,
 1827: # and feed that to the history.go() call in the helper rendering routines.
 1828: # If done correctly, the helper itself can keep track of how many times
 1829: # it renders the same states, so it doesn't go in just this state, and
 1830: # you can lean on the browser back button to make sure it all chains
 1831: # correctly.
 1832: # Right now, though, I'm just forcing all folders open.
 1833: 
 1834: sub render {
 1835:     my $self = shift;
 1836:     my $result = "";
 1837:     my $var = $self->{'variable'};
 1838:     my $curVal = $helper->{VARS}->{$var};
 1839: 
 1840:     my $buttons = '';
 1841: 
 1842:     if ($self->{'multichoice'}) {
 1843:         $result = <<SCRIPT;
 1844: <script>
 1845:     function checkall(value, checkName) {
 1846: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
 1847:             ele = document.forms.helpform.elements[i];
 1848:             if (ele.name == checkName + '.forminput') {
 1849:                 document.forms.helpform.elements[i].checked=value;
 1850:             }
 1851:         }
 1852:     }
 1853: </script>
 1854: SCRIPT
 1855:         $buttons = <<BUTTONS;
 1856: <br /> &nbsp;
 1857: <input type="button" onclick="checkall(true, '$var')" value="Select All Resources" />
 1858: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Resources" />
 1859: <br /> &nbsp;
 1860: BUTTONS
 1861:     }
 1862: 
 1863:     if (defined $self->{ERROR_MSG}) {
 1864:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 1865:     }
 1866: 
 1867:     $result .= $buttons;
 1868: 
 1869:     my $filterFunc = $self->{FILTER_FUNC};
 1870:     my $choiceFunc = $self->{CHOICE_FUNC};
 1871:     my $valueFunc = $self->{VALUE_FUNC};
 1872:     my $multichoice = $self->{'multichoice'};
 1873: 
 1874:     # Evaluate the map url as needed
 1875:     my $mapUrl;
 1876:     if ($self->{EVALUATE_MAP_URL}) {
 1877: 	my $mapUrlFunc = eval('sub { my $helper = shift; my $state = shift; ' . 
 1878: 	    $self->{MAP_URL} . '}');
 1879: 	$mapUrl = &$mapUrlFunc($helper, $self);
 1880:     } else {
 1881: 	$mapUrl = $self->{MAP_URL};
 1882:     }
 1883: 
 1884:     # Create the composite function that renders the column on the nav map
 1885:     # have to admit any language that lets me do this can't be all bad
 1886:     #  - Jeremy (Pythonista) ;-)
 1887:     my $checked = 0;
 1888:     my $renderColFunc = sub {
 1889:         my ($resource, $part, $params) = @_;
 1890: 
 1891:         my $inputType;
 1892:         if ($multichoice) { $inputType = 'checkbox'; }
 1893:         else {$inputType = 'radio'; }
 1894: 
 1895:         if (!&$choiceFunc($resource)) {
 1896:             return '<td>&nbsp;</td>';
 1897:         } else {
 1898:             my $col = "<td><input type='$inputType' name='${var}.forminput' ";
 1899:             if (!$checked && !$multichoice) {
 1900:                 $col .= "checked ";
 1901:                 $checked = 1;
 1902:             }
 1903: 	    if ($multichoice) { # all resources start checked; see bug 1174
 1904: 		$col .= "checked ";
 1905: 		$checked = 1;
 1906: 	    }
 1907:             $col .= "value='" . 
 1908:                 HTML::Entities::encode(&$valueFunc($resource)) 
 1909:                 . "' /></td>";
 1910:             return $col;
 1911:         }
 1912:     };
 1913: 
 1914:     $ENV{'form.condition'} = !$self->{'toponly'};
 1915:     my $cols = [$renderColFunc, Apache::lonnavmaps::resource()];
 1916:     if ($self->{'addstatus'}) {
 1917: 	push @$cols, (Apache::lonnavmaps::part_status_summary());
 1918: 	
 1919:     }
 1920:     $result .= 
 1921:         &Apache::lonnavmaps::render( { 'cols' => $cols,
 1922:                                        'showParts' => 0,
 1923:                                        'filterFunc' => $filterFunc,
 1924:                                        'resource_no_folder_link' => 1,
 1925:                                        'suppressEmptySequences' => $self->{'suppressEmptySequences'},
 1926:                                        'iterator_map' => $mapUrl }
 1927:                                        );
 1928: 
 1929:     $result .= $buttons;
 1930:                                                 
 1931:     return $result;
 1932: }
 1933:     
 1934: sub postprocess {
 1935:     my $self = shift;
 1936: 
 1937:     if ($self->{'multichoice'} && !$helper->{VARS}->{$self->{'variable'}}) {
 1938:         $self->{ERROR_MSG} = 'You must choose at least one resource to continue.';
 1939:         return 0;
 1940:     }
 1941: 
 1942:     if (defined($self->{NEXTSTATE})) {
 1943:         $helper->changeState($self->{NEXTSTATE});
 1944:     }
 1945: 
 1946:     return 1;
 1947: }
 1948: 
 1949: 1;
 1950: 
 1951: package Apache::lonhelper::student;
 1952: 
 1953: =pod
 1954: 
 1955: =head2 Element: studentX<student, helper element>
 1956: 
 1957: Student elements display a choice of students enrolled in the current
 1958: course. Currently it is primitive; this is expected to evolve later.
 1959: 
 1960: Student elements take the following attributes: 
 1961: 
 1962: =over 4
 1963: 
 1964: =item * B<variable>: 
 1965: 
 1966: Does what it usually does: declare which helper variable to put the
 1967: result in.
 1968: 
 1969: =item * B<multichoice>: 
 1970: 
 1971: If true allows the user to select multiple students. Defaults to false.
 1972: 
 1973: =item * B<coursepersonnel>: 
 1974: 
 1975: If true adds the course personnel to the top of the student
 1976: selection. Defaults to false.
 1977: 
 1978: =item * B<activeonly>:
 1979: 
 1980: If true, only active students and course personnel will be
 1981: shown. Defaults to false.
 1982: 
 1983: =back
 1984: 
 1985: =cut
 1986: 
 1987: no strict;
 1988: @ISA = ("Apache::lonhelper::element");
 1989: use strict;
 1990: 
 1991: 
 1992: 
 1993: BEGIN {
 1994:     &Apache::lonhelper::register('Apache::lonhelper::student',
 1995:                               ('student'));
 1996: }
 1997: 
 1998: sub new {
 1999:     my $ref = Apache::lonhelper::element->new();
 2000:     bless($ref);
 2001: }
 2002: 
 2003: sub start_student {
 2004:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2005: 
 2006:     if ($target ne 'helper') {
 2007:         return '';
 2008:     }
 2009: 
 2010:     $paramHash->{'variable'} = $token->[2]{'variable'};
 2011:     $helper->declareVar($paramHash->{'variable'});
 2012:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 2013:     $paramHash->{'coursepersonnel'} = $token->[2]{'coursepersonnel'};
 2014:     $paramHash->{'sctiveonly'} = $token->[2]{'activeonly'};
 2015:     if (defined($token->[2]{'nextstate'})) {
 2016:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
 2017:     }
 2018:     
 2019: }    
 2020: 
 2021: sub end_student {
 2022:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2023: 
 2024:     if ($target ne 'helper') {
 2025:         return '';
 2026:     }
 2027:     Apache::lonhelper::student->new();
 2028: }
 2029: 
 2030: sub render {
 2031:     my $self = shift;
 2032:     my $result = '';
 2033:     my $buttons = '';
 2034:     my $var = $self->{'variable'};
 2035: 
 2036:     if ($self->{'multichoice'}) {
 2037:         $result = <<SCRIPT;
 2038: <script>
 2039:     function checkall(value, checkName) {
 2040: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
 2041:             ele = document.forms.helpform.elements[i];
 2042:             if (ele.name == checkName + '.forminput') {
 2043:                 document.forms.helpform.elements[i].checked=value;
 2044:             }
 2045:         }
 2046:     }
 2047: </script>
 2048: SCRIPT
 2049:         $buttons = <<BUTTONS;
 2050: <br />
 2051: <input type="button" onclick="checkall(true, '$var')" value="Select All Students" />
 2052: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Students" />
 2053: <br />
 2054: BUTTONS
 2055:     }
 2056: 
 2057:     if (defined $self->{ERROR_MSG}) {
 2058:         $result .= '<font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 2059:     }
 2060: 
 2061:     my $choices = [];
 2062: 
 2063:     # Load up the non-students, if necessary
 2064:     if ($self->{'coursepersonnel'}) {
 2065: 	my %coursepersonnel = Apache::lonnet::get_course_adv_roles();
 2066: 	for (sort keys %coursepersonnel) {
 2067: 	    for my $role (split /,/, $coursepersonnel{$_}) {
 2068: 		# extract the names so we can sort them
 2069: 		my @people;
 2070: 		
 2071: 		for (split /,/, $role) {
 2072: 		    push @people, [split /:/, $role];
 2073: 		}
 2074: 		
 2075: 		@people = sort { $a->[0] cmp $b->[0] } @people;
 2076: 		
 2077: 		for my $person (@people) {
 2078: 		    push @$choices, [join(':', @$person), $person->[0], '', $_];
 2079: 		}
 2080: 	    }
 2081: 	}
 2082:     }
 2083: 
 2084:     # Constants
 2085:     my $section = Apache::loncoursedata::CL_SECTION();
 2086:     my $fullname = Apache::loncoursedata::CL_FULLNAME();
 2087:     my $status = Apache::loncoursedata::CL_STATUS();
 2088: 
 2089:     # Load up the students
 2090:     my $classlist = &Apache::loncoursedata::get_classlist();
 2091:     my @keys = keys %{$classlist};
 2092:     # Sort by: Section, name
 2093:     @keys = sort {
 2094:         if ($classlist->{$a}->[$section] ne $classlist->{$b}->[$section]) {
 2095:             return $classlist->{$a}->[$section] cmp $classlist->{$b}->[$section];
 2096:         }
 2097:         return $classlist->{$a}->[$fullname] cmp $classlist->{$b}->[$fullname];
 2098:     } @keys;
 2099: 
 2100:     # username, fullname, section, type
 2101:     for (@keys) {
 2102: 	# Filter out inactive students if we've set "activeonly"
 2103: 	if (!$self->{'activeonly'} || $classlist->{$_}->[$status] eq
 2104: 	    'Active') {
 2105: 	    push @$choices, [$_, $classlist->{$_}->[$fullname], 
 2106: 			     $classlist->{$_}->[$section], 'Student'];
 2107: 	}
 2108:     }
 2109: 
 2110:     my $name = $self->{'coursepersonnel'} ? 'Name' : 'Student Name';
 2111:     my $type = 'radio';
 2112:     if ($self->{'multichoice'}) { $type = 'checkbox'; }
 2113:     $result .= "<table cellspacing='2' cellpadding='2' border='0'>\n";
 2114:     $result .= "<tr><td></td><td align='center'><b>$name</b></td>".
 2115:         "<td align='center'><b>Section</b></td>" . 
 2116: 	"<td align='center'><b>Role</b></td></tr>";
 2117: 
 2118:     my $checked = 0;
 2119:     for my $choice (@$choices) {
 2120:         $result .= "<tr><td><input type='$type' name='" .
 2121:             $self->{'variable'} . '.forminput' . "'";
 2122:             
 2123:         if (!$self->{'multichoice'} && !$checked) {
 2124:             $result .= " checked ";
 2125:             $checked = 1;
 2126:         }
 2127:         $result .=
 2128:             " value='" . HTML::Entities::encode($choice->[0] . ':' . $choice->[2])
 2129:             . "' /></td><td>"
 2130:             . HTML::Entities::encode($choice->[1])
 2131:             . "</td><td align='center'>" 
 2132:             . HTML::Entities::encode($choice->[2])
 2133:             . "</td>\n<td>" 
 2134: 	    . HTML::Entities::encode($choice->[3]) . "</td></tr>\n";
 2135:     }
 2136: 
 2137:     $result .= "</table>\n\n";
 2138:     $result .= $buttons;    
 2139:     
 2140:     return $result;
 2141: }
 2142: 
 2143: sub postprocess {
 2144:     my $self = shift;
 2145: 
 2146:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
 2147:     if (!$result) {
 2148:         $self->{ERROR_MSG} = 'You must choose at least one student '.
 2149:             'to continue.';
 2150:         return 0;
 2151:     }
 2152: 
 2153:     if (defined($self->{NEXTSTATE})) {
 2154:         $helper->changeState($self->{NEXTSTATE});
 2155:     }
 2156: 
 2157:     return 1;
 2158: }
 2159: 
 2160: 1;
 2161: 
 2162: package Apache::lonhelper::files;
 2163: 
 2164: =pod
 2165: 
 2166: =head2 Element: filesX<files, helper element>
 2167: 
 2168: files allows the users to choose files from a given directory on the
 2169: server. It is always multichoice and stores the result as a triple-pipe
 2170: delimited entry in the helper variables. 
 2171: 
 2172: Since it is extremely unlikely that you can actually code a constant
 2173: representing the directory you wish to allow the user to search, <files>
 2174: takes a subroutine that returns the name of the directory you wish to
 2175: have the user browse.
 2176: 
 2177: files accepts the attribute "variable" to control where the files chosen
 2178: are put. It accepts the attribute "multichoice" as the other attribute,
 2179: defaulting to false, which if true will allow the user to select more
 2180: then one choice. 
 2181: 
 2182: <files> accepts three subtags: 
 2183: 
 2184: =over 4
 2185: 
 2186: =item * B<nextstate>: works as it does with the other tags. 
 2187: 
 2188: =item * B<filechoice>: When the contents of this tag are surrounded by
 2189:     "sub {" and "}", will return a string representing what directory
 2190:     on the server to allow the user to choose files from. 
 2191: 
 2192: =item * B<filefilter>: Should contain Perl code that when surrounded
 2193:     by "sub { my $filename = shift; " and "}", returns a true value if
 2194:     the user can pick that file, or false otherwise. The filename
 2195:     passed to the function will be just the name of the file, with no
 2196:     path info. By default, a filter function will be used that will
 2197:     mask out old versions of files. This function is available as
 2198:     Apache::lonhelper::files::not_old_version if you want to use it to
 2199:     composite your own filters.
 2200: 
 2201: =back
 2202: 
 2203: B<General security note>: You should ensure the user can not somehow 
 2204: pass something into your code that would allow them to look places 
 2205: they should not be able to see, like the C</etc/> directory. However,
 2206: the security impact would be minimal, since it would only expose
 2207: the existence of files, there should be no way to parlay that into
 2208: viewing the files. 
 2209: 
 2210: =cut
 2211: 
 2212: no strict;
 2213: @ISA = ("Apache::lonhelper::element");
 2214: use strict;
 2215: 
 2216: use Apache::lonpubdir; # for getTitleString
 2217: 
 2218: BEGIN {
 2219:     &Apache::lonhelper::register('Apache::lonhelper::files',
 2220:                                  ('files', 'filechoice', 'filefilter'));
 2221: }
 2222: 
 2223: sub not_old_version {
 2224:     my $file = shift;
 2225:     
 2226:     # Given a file name, return false if it is an "old version" of a
 2227:     # file, or true if it is not.
 2228: 
 2229:     if ($file =~ /^.*\.[0-9]+\.[A-Za-z]+(\.meta)?$/) {
 2230: 	return 0;
 2231:     }
 2232:     return 1;
 2233: }
 2234: 
 2235: sub new {
 2236:     my $ref = Apache::lonhelper::element->new();
 2237:     bless($ref);
 2238: }
 2239: 
 2240: sub start_files {
 2241:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2242: 
 2243:     if ($target ne 'helper') {
 2244:         return '';
 2245:     }
 2246:     $paramHash->{'variable'} = $token->[2]{'variable'};
 2247:     $helper->declareVar($paramHash->{'variable'});
 2248:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 2249: }    
 2250: 
 2251: sub end_files {
 2252:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2253: 
 2254:     if ($target ne 'helper') {
 2255:         return '';
 2256:     }
 2257:     if (!defined($paramHash->{FILTER_FUNC})) {
 2258:         $paramHash->{FILTER_FUNC} = sub { return 1; };
 2259:     }
 2260:     Apache::lonhelper::files->new();
 2261: }    
 2262: 
 2263: sub start_filechoice {
 2264:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2265: 
 2266:     if ($target ne 'helper') {
 2267:         return '';
 2268:     }
 2269:     $paramHash->{'filechoice'} = Apache::lonxml::get_all_text('/filechoice',
 2270:                                                               $parser);
 2271: }
 2272: 
 2273: sub end_filechoice { return ''; }
 2274: 
 2275: sub start_filefilter {
 2276:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2277: 
 2278:     if ($target ne 'helper') {
 2279:         return '';
 2280:     }
 2281: 
 2282:     my $contents = Apache::lonxml::get_all_text('/filefilter',
 2283:                                                 $parser);
 2284:     $contents = 'sub { my $filename = shift; ' . $contents . '}';
 2285:     $paramHash->{FILTER_FUNC} = eval $contents;
 2286: }
 2287: 
 2288: sub end_filefilter { return ''; }
 2289: 
 2290: sub render {
 2291:     my $self = shift;
 2292:     my $result = '';
 2293:     my $var = $self->{'variable'};
 2294:     
 2295:     my $subdirFunc = eval('sub {' . $self->{'filechoice'} . '}');
 2296:     die 'Error in resource filter code for variable ' . 
 2297:         {'variable'} . ', Perl said:' . $@ if $@;
 2298: 
 2299:     my $subdir = &$subdirFunc();
 2300: 
 2301:     my $filterFunc = $self->{FILTER_FUNC};
 2302:     if (!defined($filterFunc)) {
 2303: 	$filterFunc = &not_old_version;
 2304:     }
 2305:     my $buttons = '';
 2306:     my $type = 'radio';
 2307:     if ($self->{'multichoice'}) {
 2308:         $type = 'checkbox';
 2309:     }
 2310: 
 2311:     if ($self->{'multichoice'}) {
 2312:         $result = <<SCRIPT;
 2313: <script>
 2314:     function checkall(value, checkName) {
 2315: 	for (i=0; i<document.forms.helpform.elements.length; i++) {
 2316:             ele = document.forms.helpform.elements[i];
 2317:             if (ele.name == checkName + '.forminput') {
 2318:                 document.forms.helpform.elements[i].checked=value;
 2319:             }
 2320:         }
 2321:     }
 2322: 
 2323:     function checkallclass(value, className) {
 2324:         for (i=0; i<document.forms.helpform.elements.length; i++) {
 2325:             ele = document.forms.helpform.elements[i];
 2326:             if (ele.type == "$type" && ele.onclick) {
 2327:                 document.forms.helpform.elements[i].checked=value;
 2328:             }
 2329:         }
 2330:     }
 2331: </script>
 2332: SCRIPT
 2333:         $buttons = <<BUTTONS;
 2334: <br /> &nbsp;
 2335: <input type="button" onclick="checkall(true, '$var')" value="Select All Files" />
 2336: <input type="button" onclick="checkall(false, '$var')" value="Unselect All Files" />
 2337: BUTTONS
 2338: 
 2339:         if ($helper->{VARS}->{'construction'}) {
 2340:             $buttons .= <<BUTTONS;
 2341: <input type="button" onclick="checkallclass(true, 'Published')" value="Select All Published" />
 2342: <input type="button" onclick="checkallclass(false, 'Published')" value="Unselect All Published" />
 2343: <br /> &nbsp;
 2344: BUTTONS
 2345:        }
 2346:     }
 2347: 
 2348:     # Get the list of files in this directory.
 2349:     my @fileList;
 2350: 
 2351:     # If the subdirectory is in local CSTR space
 2352:     my $metadir;
 2353:     if ($subdir =~ m|/home/([^/]+)/public_html/(.*)|) {
 2354:         my $user = $1;
 2355:         my $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 2356: 	$metadir='/res/'.$domain.'/'.$user.'/'.$2;
 2357:         @fileList = &Apache::lonnet::dirlist($subdir, $domain, $user, '');
 2358:     } elsif ($subdir =~ m|^~([^/]+)/(.*)$|) {
 2359: 	$subdir='/home/'.$1.'/public_html/'.$2;
 2360:         my $user = $1;
 2361:         my $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 2362: 	$metadir='/res/'.$domain.'/'.$user.'/'.$2;
 2363:         @fileList = &Apache::lonnet::dirlist($subdir, $domain, $user, '');
 2364:     } else {
 2365:         # local library server resource space
 2366:         @fileList = &Apache::lonnet::dirlist($subdir, $ENV{'user.domain'}, $ENV{'user.name'}, '');
 2367:     }
 2368: 
 2369:     # Sort the fileList into order
 2370:     @fileList = sort @fileList;
 2371: 
 2372:     $result .= $buttons;
 2373: 
 2374:     if (defined $self->{ERROR_MSG}) {
 2375:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 2376:     }
 2377: 
 2378:     $result .= '<table border="0" cellpadding="2" cellspacing="0">';
 2379: 
 2380:     # Keeps track if there are no choices, prints appropriate error
 2381:     # if there are none. 
 2382:     my $choices = 0;
 2383:     # Print each legitimate file choice.
 2384:     for my $file (@fileList) {
 2385:         $file = (split(/&/, $file))[0];
 2386:         if ($file eq '.' || $file eq '..') {
 2387:             next;
 2388:         }
 2389:         my $fileName = $subdir .'/'. $file;
 2390:         if (&$filterFunc($file)) {
 2391: 	    my $status;
 2392: 	    my $color;
 2393: 	    if ($helper->{VARS}->{'construction'}) {
 2394: 		($status, $color) = @{fileState($subdir, $file)};
 2395: 	    } else {
 2396: 		$status = '';
 2397: 		$color = '';
 2398: 	    }
 2399: 
 2400:             # Get the title
 2401:             my $title = Apache::lonpubdir::getTitleString(($metadir?$metadir:$subdir) .'/'. $file);
 2402: 
 2403:             # Netscape 4 is stupid and there's nowhere to put the
 2404:             # information on the input tag that the file is Published,
 2405:             # Unpublished, etc. In *real* browsers we can just say
 2406:             # "class='Published'" and check the className attribute of
 2407:             # the input tag, but Netscape 4 is too stupid to understand
 2408:             # that attribute, and un-comprehended attributes are not
 2409:             # reflected into the object model. So instead, what I do 
 2410:             # is either have or don't have an "onclick" handler that 
 2411:             # does nothing, give Published files the onclick handler, and
 2412:             # have the checker scripts check for that. Stupid and clumsy,
 2413:             # and only gives us binary "yes/no" information (at least I
 2414:             # couldn't figure out how to reach into the event handler's
 2415:             # actual code to retreive a value), but it works well enough
 2416:             # here.
 2417:         
 2418:             my $onclick = '';
 2419:             if ($status eq 'Published' && $helper->{VARS}->{'construction'}) {
 2420:                 $onclick = 'onclick="a=1" ';
 2421:             }
 2422:             $result .= '<tr><td align="right"' . " bgcolor='$color'>" .
 2423:                 "<input $onclick type='$type' name='" . $var
 2424:             . ".forminput' value='" . HTML::Entities::encode($fileName) .
 2425:                 "'";
 2426:             if (!$self->{'multichoice'} && $choices == 0) {
 2427:                 $result .= ' checked';
 2428:             }
 2429:             $result .= "/></td><td bgcolor='$color'>" . $file . "</td>" .
 2430:                 "<td bgcolor='$color'>$title</td>" .
 2431:                 "<td bgcolor='$color'>$status</td>" . "</tr>\n";
 2432:             $choices++;
 2433:         }
 2434:     }
 2435: 
 2436:     $result .= "</table>\n";
 2437: 
 2438:     if (!$choices) {
 2439:         $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 />';
 2440:     }
 2441: 
 2442:     $result .= $buttons;
 2443: 
 2444:     return $result;
 2445: }
 2446: 
 2447: # Determine the state of the file: Published, unpublished, modified.
 2448: # Return the color it should be in and a label as a two-element array
 2449: # reference.
 2450: # Logic lifted from lonpubdir.pm, even though I don't know that it's still
 2451: # the most right thing to do.
 2452: 
 2453: sub fileState {
 2454:     my $constructionSpaceDir = shift;
 2455:     my $file = shift;
 2456:     
 2457:     my $docroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2458:     my $subdirpart = $constructionSpaceDir;
 2459:     $subdirpart =~ s/^\/home\/$ENV{'user.name'}\/public_html//;
 2460:     my $resdir = $docroot . '/res/' . $ENV{'user.domain'} . '/' . $ENV{'user.name'} .
 2461:         $subdirpart;
 2462: 
 2463:     my @constructionSpaceFileStat = stat($constructionSpaceDir . '/' . $file);
 2464:     my @resourceSpaceFileStat = stat($resdir . '/' . $file);
 2465:     if (!@resourceSpaceFileStat) {
 2466:         return ['Unpublished', '#FFCCCC'];
 2467:     }
 2468: 
 2469:     my $constructionSpaceFileModified = $constructionSpaceFileStat[9];
 2470:     my $resourceSpaceFileModified = $resourceSpaceFileStat[9];
 2471:     
 2472:     if ($constructionSpaceFileModified > $resourceSpaceFileModified) {
 2473:         return ['Modified', '#FFFFCC'];
 2474:     }
 2475:     return ['Published', '#CCFFCC'];
 2476: }
 2477: 
 2478: sub postprocess {
 2479:     my $self = shift;
 2480:     my $result = $ENV{'form.' . $self->{'variable'} . '.forminput'};
 2481:     if (!$result) {
 2482:         $self->{ERROR_MSG} = 'You must choose at least one file '.
 2483:             'to continue.';
 2484:         return 0;
 2485:     }
 2486: 
 2487:     if (defined($self->{NEXTSTATE})) {
 2488:         $helper->changeState($self->{NEXTSTATE});
 2489:     }
 2490: 
 2491:     return 1;
 2492: }
 2493: 
 2494: 1;
 2495: 
 2496: package Apache::lonhelper::section;
 2497: 
 2498: =pod
 2499: 
 2500: =head2 Element: sectionX<section, helper element>
 2501: 
 2502: <section> allows the user to choose one or more sections from the current
 2503: course.
 2504: 
 2505: It takes the standard attributes "variable", "multichoice", and
 2506: "nextstate", meaning what they do for most other elements.
 2507: 
 2508: =cut
 2509: 
 2510: no strict;
 2511: @ISA = ("Apache::lonhelper::choices");
 2512: use strict;
 2513: 
 2514: BEGIN {
 2515:     &Apache::lonhelper::register('Apache::lonhelper::section',
 2516:                                  ('section'));
 2517: }
 2518: 
 2519: sub new {
 2520:     my $ref = Apache::lonhelper::choices->new();
 2521:     bless($ref);
 2522: }
 2523: 
 2524: sub start_section {
 2525:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2526: 
 2527:     if ($target ne 'helper') {
 2528:         return '';
 2529:     }
 2530: 
 2531:     $paramHash->{CHOICES} = [];
 2532: 
 2533:     $paramHash->{'variable'} = $token->[2]{'variable'};
 2534:     $helper->declareVar($paramHash->{'variable'});
 2535:     $paramHash->{'multichoice'} = $token->[2]{'multichoice'};
 2536:     if (defined($token->[2]{'nextstate'})) {
 2537:         $paramHash->{NEXTSTATE} = $token->[2]{'nextstate'};
 2538:     }
 2539: 
 2540:     # Populate the CHOICES element
 2541:     my %choices;
 2542: 
 2543:     my $section = Apache::loncoursedata::CL_SECTION();
 2544:     my $classlist = Apache::loncoursedata::get_classlist();
 2545:     foreach (keys %$classlist) {
 2546:         my $sectionName = $classlist->{$_}->[$section];
 2547:         if (!$sectionName) {
 2548:             $choices{"No section assigned"} = "";
 2549:         } else {
 2550:             $choices{$sectionName} = $sectionName;
 2551:         }
 2552:     } 
 2553:    
 2554:     for my $sectionName (sort(keys(%choices))) {
 2555:         
 2556:         push @{$paramHash->{CHOICES}}, [$sectionName, $sectionName];
 2557:     }
 2558: }    
 2559: 
 2560: sub end_section {
 2561:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2562: 
 2563:     if ($target ne 'helper') {
 2564:         return '';
 2565:     }
 2566:     Apache::lonhelper::section->new();
 2567: }    
 2568: 1;
 2569: 
 2570: package Apache::lonhelper::string;
 2571: 
 2572: =pod
 2573: 
 2574: =head2 Element: stringX<string, helper element>
 2575: 
 2576: string elements provide a string entry field for the user. string elements
 2577: take the usual 'variable' and 'nextstate' parameters. string elements
 2578: also pass through 'maxlength' and 'size' attributes to the input tag.
 2579: 
 2580: string honors the defaultvalue tag, if given.
 2581: 
 2582: string honors the validation function, if given.
 2583: 
 2584: =cut
 2585: 
 2586: no strict;
 2587: @ISA = ("Apache::lonhelper::element");
 2588: use strict;
 2589: 
 2590: BEGIN {
 2591:     &Apache::lonhelper::register('Apache::lonhelper::string',
 2592:                               ('string'));
 2593: }
 2594: 
 2595: sub new {
 2596:     my $ref = Apache::lonhelper::element->new();
 2597:     bless($ref);
 2598: }
 2599: 
 2600: # CONSTRUCTION: Construct the message element from the XML
 2601: sub start_string {
 2602:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2603: 
 2604:     if ($target ne 'helper') {
 2605:         return '';
 2606:     }
 2607: 
 2608:     $paramHash->{'variable'} = $token->[2]{'variable'};
 2609:     $helper->declareVar($paramHash->{'variable'});
 2610:     $paramHash->{'nextstate'} = $token->[2]{'nextstate'};
 2611:     $paramHash->{'maxlength'} = $token->[2]{'maxlength'};
 2612:     $paramHash->{'size'} = $token->[2]{'size'};
 2613: 
 2614:     return '';
 2615: }
 2616: 
 2617: sub end_string {
 2618:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2619: 
 2620:     if ($target ne 'helper') {
 2621:         return '';
 2622:     }
 2623:     Apache::lonhelper::string->new();
 2624:     return '';
 2625: }
 2626: 
 2627: sub render {
 2628:     my $self = shift;
 2629:     my $result = '';
 2630: 
 2631:     if (defined $self->{ERROR_MSG}) {
 2632:         $result .= '<br /><font color="#FF0000">' . $self->{ERROR_MSG} . '</font><br /><br />';
 2633:     }
 2634: 
 2635:     $result .= '<input type="string" name="' . $self->{'variable'} . '.forminput"';
 2636: 
 2637:     if (defined($self->{'size'})) {
 2638:         $result .= ' size="' . $self->{'size'} . '"';
 2639:     }
 2640:     if (defined($self->{'maxlength'})) {
 2641:         $result .= ' maxlength="' . $self->{'maxlength'} . '"';
 2642:     }
 2643: 
 2644:     if (defined($self->{DEFAULT_VALUE})) {
 2645:         my $valueFunc = eval($self->{DEFAULT_VALUE});
 2646:         die 'Error in default value code for variable ' . 
 2647:             $self->{'variable'} . ', Perl said: ' . $@ if $@;
 2648:         $result .= ' value="' . &$valueFunc($helper, $self) . '"';
 2649:     }
 2650: 
 2651:     $result .= ' />';
 2652: 
 2653:     return $result;
 2654: }
 2655: 
 2656: # If a NEXTSTATE was given, switch to it
 2657: sub postprocess {
 2658:     my $self = shift;
 2659: 
 2660:     if (defined($self->{VALIDATOR})) {
 2661: 	my $validator = eval($self->{VALIDATOR});
 2662: 	die 'Died during evaluation of evaulation code; Perl said: ' . $@ if $@;
 2663: 	my $invalid = &$validator($helper, $state, $self, $self->getValue());
 2664: 	if ($invalid) {
 2665: 	    $self->{ERROR_MSG} = $invalid;
 2666: 	    return 0;
 2667: 	}
 2668:     }
 2669: 
 2670:     if (defined($self->{'nextstate'})) {
 2671:         $helper->changeState($self->{'nextstate'});
 2672:     }
 2673: 
 2674:     return 1;
 2675: }
 2676: 
 2677: 1;
 2678: 
 2679: package Apache::lonhelper::general;
 2680: 
 2681: =pod
 2682: 
 2683: =head2 General-purpose tag: <exec>X<exec, helper tag>
 2684: 
 2685: The contents of the exec tag are executed as Perl code, B<not> inside a 
 2686: safe space, so the full range of $ENV and such is available. The code
 2687: will be executed as a subroutine wrapped with the following code:
 2688: 
 2689: "sub { my $helper = shift; my $state = shift;" and
 2690: 
 2691: "}"
 2692: 
 2693: The return value is ignored.
 2694: 
 2695: $helper is the helper object. Feel free to add methods to the helper
 2696: object to support whatever manipulation you may need to do (for instance,
 2697: overriding the form location if the state is the final state; see 
 2698: parameter.helper for an example).
 2699: 
 2700: $state is the $paramHash that has currently been generated and may
 2701: be manipulated by the code in exec. Note that the $state is not yet
 2702: an actual state B<object>, it is just a hash, so do not expect to
 2703: be able to call methods on it.
 2704: 
 2705: =cut
 2706: 
 2707: BEGIN {
 2708:     &Apache::lonhelper::register('Apache::lonhelper::general',
 2709:                                  'exec', 'condition', 'clause',
 2710:                                  'eval');
 2711: }
 2712: 
 2713: sub start_exec {
 2714:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2715: 
 2716:     if ($target ne 'helper') {
 2717:         return '';
 2718:     }
 2719:     
 2720:     my $code = &Apache::lonxml::get_all_text('/exec', $parser);
 2721:     
 2722:     $code = eval ('sub { my $helper = shift; my $state = shift; ' .
 2723:         $code . "}");
 2724:     die 'Error in <exec>, Perl said: '. $@ if $@;
 2725:     &$code($helper, $paramHash);
 2726: }
 2727: 
 2728: sub end_exec { return ''; }
 2729: 
 2730: =pod
 2731: 
 2732: =head2 General-purpose tag: <condition>
 2733: 
 2734: The <condition> tag allows you to mask out parts of the helper code
 2735: depending on some programatically determined condition. The condition
 2736: tag contains a tag <clause> which contains perl code that when wrapped
 2737: with "sub { my $helper = shift; my $state = shift; " and "}", returns
 2738: a true value if the XML in the condition should be evaluated as a normal
 2739: part of the helper, or false if it should be completely discarded.
 2740: 
 2741: The <clause> tag must be the first sub-tag of the <condition> tag or
 2742: it will not work as expected.
 2743: 
 2744: =cut
 2745: 
 2746: # The condition tag just functions as a marker, it doesn't have
 2747: # to "do" anything. Technically it doesn't even have to be registered
 2748: # with the lonxml code, but I leave this here to be explicit about it.
 2749: sub start_condition { return ''; }
 2750: sub end_condition { return ''; }
 2751: 
 2752: sub start_clause {
 2753:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2754: 
 2755:     if ($target ne 'helper') {
 2756:         return '';
 2757:     }
 2758:     
 2759:     my $clause = Apache::lonxml::get_all_text('/clause', $parser);
 2760:     $clause = eval('sub { my $helper = shift; my $state = shift; '
 2761:         . $clause . '}');
 2762:     die 'Error in clause of condition, Perl said: ' . $@ if $@;
 2763:     if (!&$clause($helper, $paramHash)) {
 2764:         # Discard all text until the /condition.
 2765:         &Apache::lonxml::get_all_text('/condition', $parser);
 2766:     }
 2767: }
 2768: 
 2769: sub end_clause { return ''; }
 2770: 
 2771: =pod
 2772: 
 2773: =head2 General-purpose tag: <eval>X<eval, helper tag>
 2774: 
 2775: The <eval> tag will be evaluated as a subroutine call passed in the
 2776: current helper object and state hash as described in <condition> above,
 2777: but is expected to return a string to be printed directly to the
 2778: screen. This is useful for dynamically generating messages. 
 2779: 
 2780: =cut
 2781: 
 2782: # This is basically a type of message.
 2783: # Programmatically setting $paramHash->{NEXTSTATE} would work, though
 2784: # it's probably bad form.
 2785: 
 2786: sub start_eval {
 2787:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2788: 
 2789:     if ($target ne 'helper') {
 2790:         return '';
 2791:     }
 2792:     
 2793:     my $program = Apache::lonxml::get_all_text('/eval', $parser);
 2794:     $program = eval('sub { my $helper = shift; my $state = shift; '
 2795:         . $program . '}');
 2796:     die 'Error in eval code, Perl said: ' . $@ if $@;
 2797:     $paramHash->{MESSAGE_TEXT} = &$program($helper, $paramHash);
 2798: }
 2799: 
 2800: sub end_eval { 
 2801:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2802: 
 2803:     if ($target ne 'helper') {
 2804:         return '';
 2805:     }
 2806: 
 2807:     Apache::lonhelper::message->new();
 2808: }
 2809: 
 2810: 1;
 2811: 
 2812: package Apache::lonhelper::final;
 2813: 
 2814: =pod
 2815: 
 2816: =head2 Element: finalX<final, helper tag>
 2817: 
 2818: <final> is a special element that works with helpers that use the <finalcode>
 2819: tagX<finalcode, helper tag>. It goes through all the states and elements, executing the <finalcode>
 2820: snippets and collecting the results. Finally, it takes the user out of the
 2821: helper, going to a provided page.
 2822: 
 2823: If the parameter "restartCourse" is true, this will override the buttons and
 2824: will make a "Finish Helper" button that will re-initialize the course for them,
 2825: which is useful for the Course Initialization helper so the users never see
 2826: the old values taking effect.
 2827: 
 2828: =cut
 2829: 
 2830: no strict;
 2831: @ISA = ("Apache::lonhelper::element");
 2832: use strict;
 2833: 
 2834: BEGIN {
 2835:     &Apache::lonhelper::register('Apache::lonhelper::final',
 2836:                                  ('final', 'exitpage'));
 2837: }
 2838: 
 2839: sub new {
 2840:     my $ref = Apache::lonhelper::element->new();
 2841:     bless($ref);
 2842: }
 2843: 
 2844: sub start_final { 
 2845:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2846: 
 2847:     if ($target ne 'helper') {
 2848:         return '';
 2849:     }
 2850: 
 2851:     $paramHash->{'restartCourse'} = $token->[2]{'restartCourse'};
 2852: 
 2853:     return ''; 
 2854: }
 2855: 
 2856: sub end_final {
 2857:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2858: 
 2859:     if ($target ne 'helper') {
 2860:         return '';
 2861:     }
 2862: 
 2863:     Apache::lonhelper::final->new();
 2864:    
 2865:     return '';
 2866: }
 2867: 
 2868: sub start_exitpage {
 2869:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2870: 
 2871:     if ($target ne 'helper') {
 2872:         return '';
 2873:     }
 2874: 
 2875:     $paramHash->{EXIT_PAGE} = &Apache::lonxml::get_all_text('/exitpage',
 2876:                                                             $parser);
 2877: 
 2878:     return '';
 2879: }
 2880: 
 2881: sub end_exitpage { return ''; }
 2882: 
 2883: sub render {
 2884:     my $self = shift;
 2885: 
 2886:     my @results;
 2887: 
 2888:     # Collect all the results
 2889:     for my $stateName (keys %{$helper->{STATES}}) {
 2890:         my $state = $helper->{STATES}->{$stateName};
 2891:         
 2892:         for my $element (@{$state->{ELEMENTS}}) {
 2893:             if (defined($element->{FINAL_CODE})) {
 2894:                 # Compile the code.
 2895:                 my $code = 'sub { my $helper = shift; my $element = shift; ' 
 2896:                     . $element->{FINAL_CODE} . '}';
 2897:                 $code = eval($code);
 2898:                 die 'Error while executing final code for element with var ' .
 2899:                     $element->{'variable'} . ', Perl said: ' . $@ if $@;
 2900: 
 2901:                 my $result = &$code($helper, $element);
 2902:                 if ($result) {
 2903:                     push @results, $result;
 2904:                 }
 2905:             }
 2906:         }
 2907:     }
 2908: 
 2909:     my $result;
 2910: 
 2911:     if (scalar(@results) != 0) {
 2912: 	$result .= "<ul>\n";
 2913: 	for my $re (@results) {
 2914: 	    $result .= '    <li>' . $re . "</li>\n";
 2915: 	}
 2916: 	
 2917: 	if (!@results) {
 2918: 	    $result .= '    <li>No changes were made to current settings.</li>';
 2919: 	}
 2920: 	
 2921: 	$result .= '</ul>';
 2922:     }
 2923: 
 2924:     if ($self->{'restartCourse'}) {
 2925: 	my $targetURL = '/adm/menu';
 2926: 	if ($ENV{'course.'.$ENV{'request.course.id'}.'.clonedfrom'}) {
 2927: 	    $targetURL = '/adm/parmset?overview=1';
 2928: 	}
 2929:         $result .= "<center>\n" .
 2930:             "<form action='/adm/roles' method='post' target='loncapaclient'>\n" .
 2931:             "<input type='button' onclick='history.go(-1)' value='&lt;- Previous' />" .
 2932:             "<input type='hidden' name='orgurl' value='$targetURL' />" .
 2933:             "<input type='hidden' name='selectrole' value='1' />\n" .
 2934:             "<input type='hidden' name='" . $ENV{'request.role'} . 
 2935:             "' value='1' />\n<input type='submit' value='Finish Course Initialization' />\n" .
 2936:             "</form></center>";
 2937:     }
 2938: 
 2939:     return $result;
 2940: }
 2941: 
 2942: sub overrideForm {
 2943:     my $self = shift;
 2944:     return $self->{'restartCourse'};
 2945: }
 2946: 
 2947: 1;
 2948: 
 2949: package Apache::lonhelper::parmwizfinal;
 2950: 
 2951: # This is the final state for the parmwizard. It is not generally useful,
 2952: # so it is not perldoc'ed. It does its own processing.
 2953: # It is represented with <parmwizfinal />, and
 2954: # should later be moved to lonparmset.pm .
 2955: 
 2956: no strict;
 2957: @ISA = ('Apache::lonhelper::element');
 2958: use strict;
 2959: 
 2960: BEGIN {
 2961:     &Apache::lonhelper::register('Apache::lonhelper::parmwizfinal',
 2962:                                  ('parmwizfinal'));
 2963: }
 2964: 
 2965: use Time::localtime;
 2966: 
 2967: sub new {
 2968:     my $ref = Apache::lonhelper::choices->new();
 2969:     bless ($ref);
 2970: }
 2971: 
 2972: sub start_parmwizfinal { return ''; }
 2973: 
 2974: sub end_parmwizfinal {
 2975:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2976: 
 2977:     if ($target ne 'helper') {
 2978:         return '';
 2979:     }
 2980:     Apache::lonhelper::parmwizfinal->new();
 2981: }
 2982: 
 2983: # Renders a form that, when submitted, will form the input to lonparmset.pm
 2984: sub render {
 2985:     my $self = shift;
 2986:     my $vars = $helper->{VARS};
 2987: 
 2988:     # FIXME: Unify my designators with the standard ones
 2989:     my %dateTypeHash = ('open_date' => "opening date",
 2990:                         'due_date' => "due date",
 2991:                         'answer_date' => "answer date",
 2992: 			'tries' => 'number of tries',
 2993: 			'weight' => 'problem weight'
 2994: 			);
 2995:     my %parmTypeHash = ('open_date' => "0_opendate",
 2996:                         'due_date' => "0_duedate",
 2997:                         'answer_date' => "0_answerdate",
 2998: 			'tries' => '0_maxtries',
 2999: 			'weight' => '0_weight' );
 3000:     
 3001:     my $affectedResourceId = "";
 3002:     my $parm_name = $parmTypeHash{$vars->{ACTION_TYPE}};
 3003:     my $level = "";
 3004:     my $resourceString;
 3005:     my $symb;
 3006:     my $paramlevel;
 3007: 
 3008:     # Print the granularity, depending on the action
 3009:     if ($vars->{GRANULARITY} eq 'whole_course') {
 3010:         $resourceString .= '<li>for <b>all resources in the course</b></li>';
 3011:         $level = 9; # general course, see lonparmset.pm perldoc
 3012:         $affectedResourceId = "0.0";
 3013:         $symb = 'a';
 3014:         $paramlevel = 'general';
 3015:     } elsif ($vars->{GRANULARITY} eq 'map') {
 3016:         my $navmap = Apache::lonnavmaps::navmap->new();
 3017:         my $res = $navmap->getByMapPc($vars->{RESOURCE_ID});
 3018:         my $title = $res->compTitle();
 3019:         $symb = $res->symb();
 3020:         $navmap->untieHashes();
 3021:         $resourceString .= "<li>for the map named <b>$title</b></li>";
 3022:         $level = 8;
 3023:         $affectedResourceId = $vars->{RESOURCE_ID};
 3024:         $paramlevel = 'map';
 3025:     } else {
 3026:         my $navmap = Apache::lonnavmaps::navmap->new();
 3027:         my $res = $navmap->getById($vars->{RESOURCE_ID});
 3028:         $symb = $res->symb();
 3029:         my $title = $res->compTitle();
 3030:         $navmap->untieHashes();
 3031:         $resourceString .= "<li>for the resource named <b>$title</b></li>";
 3032:         $level = 7;
 3033:         $affectedResourceId = $vars->{RESOURCE_ID};
 3034:         $paramlevel = 'full';
 3035:     }
 3036: 
 3037:     my $result = "<form name='helpform' method='get' action='/adm/parmset#$affectedResourceId&$parm_name&$level'>\n";
 3038:     $result .= '<p>Confirm that this information is correct, then click &quot;Finish Wizard&quot; to complete setting the parameter.<ul>';
 3039:     
 3040:     # Print the type of manipulation:
 3041:     $result .= '<li>Setting the <b>' . $dateTypeHash{$vars->{ACTION_TYPE}} . '</b>';
 3042:     if ($vars->{ACTION_TYPE} eq 'tries') {
 3043: 	$result .= ' to <b>' . $vars->{TRIES} . '</b>';
 3044:     }
 3045:     if ($vars->{ACTION_TYPE} eq 'weight') {
 3046: 	$result .= ' to <b>' . $vars->{WEIGHT} . '</b>';
 3047:     }
 3048:     $result .= "</li>\n";
 3049:     if ($vars->{ACTION_TYPE} eq 'due_date' || 
 3050:         $vars->{ACTION_TYPE} eq 'answer_date') {
 3051:         # for due dates, we default to "date end" type entries
 3052:         $result .= "<input type='hidden' name='recent_date_end' " .
 3053:             "value='" . $vars->{PARM_DATE} . "' />\n";
 3054:         $result .= "<input type='hidden' name='pres_value' " . 
 3055:             "value='" . $vars->{PARM_DATE} . "' />\n";
 3056:         $result .= "<input type='hidden' name='pres_type' " .
 3057:             "value='date_end' />\n";
 3058:     } elsif ($vars->{ACTION_TYPE} eq 'open_date') {
 3059:         $result .= "<input type='hidden' name='recent_date_start' ".
 3060:             "value='" . $vars->{PARM_DATE} . "' />\n";
 3061:         $result .= "<input type='hidden' name='pres_value' " .
 3062:             "value='" . $vars->{PARM_DATE} . "' />\n";
 3063:         $result .= "<input type='hidden' name='pres_type' " .
 3064:             "value='date_start' />\n";
 3065:     } elsif ($vars->{ACTION_TYPE} eq 'tries') {
 3066: 	$result .= "<input type='hidden' name='pres_value' " .
 3067: 	    "value='" . $vars->{TRIES} . "' />\n";
 3068:     } elsif ($vars->{ACTION_TYPE} eq 'weight') {
 3069: 	$result .= "<input type='hidden' name='pres_value' " .
 3070: 	    "value='" . $vars->{WEIGHT} . "' />\n";
 3071:     }
 3072: 
 3073:     $result .= $resourceString;
 3074:     
 3075:     # Print targets
 3076:     if ($vars->{TARGETS} eq 'course') {
 3077:         $result .= '<li>for <b>all students in course</b></li>';
 3078:     } elsif ($vars->{TARGETS} eq 'section') {
 3079:         my $section = $vars->{SECTION_NAME};
 3080:         $result .= "<li>for section <b>$section</b></li>";
 3081:         $level -= 3;
 3082:         $result .= "<input type='hidden' name='csec' value='" .
 3083:             HTML::Entities::encode($section) . "' />\n";
 3084:     } else {
 3085:         # FIXME: This is probably wasteful! Store the name!
 3086:         my $classlist = Apache::loncoursedata::get_classlist();
 3087:         my $username = $vars->{USER_NAME};
 3088:         # Chop off everything after the last colon (section)
 3089:         $username = substr($username, 0, rindex($username, ':'));
 3090:         my $name = $classlist->{$username}->[6];
 3091:         $result .= "<li>for <b>$name</b></li>";
 3092:         $level -= 6;
 3093:         my ($uname, $udom) = split /:/, $vars->{USER_NAME};
 3094:         $result .= "<input type='hidden' name='uname' value='".
 3095:             HTML::Entities::encode($uname) . "' />\n";
 3096:         $result .= "<input type='hidden' name='udom' value='".
 3097:             HTML::Entities::encode($udom) . "' />\n";
 3098:     }
 3099: 
 3100:     # Print value
 3101:     if ($vars->{ACTION_TYPE} ne 'tries' && $vars->{ACTION_TYPE} ne 'weight') {
 3102: 	$result .= "<li>to <b>" . ctime($vars->{PARM_DATE}) . "</b> (" .
 3103: 	    Apache::lonnavmaps::timeToHumanString($vars->{PARM_DATE}) 
 3104: 	    . ")</li>\n";
 3105:     }
 3106:  
 3107:     # print pres_marker
 3108:     $result .= "\n<input type='hidden' name='pres_marker'" .
 3109:         " value='$affectedResourceId&$parm_name&$level' />\n";
 3110:     
 3111:     # Make the table appear
 3112:     $result .= "\n<input type='hidden' value='true' name='prevvisit' />";
 3113:     $result .= "\n<input type='hidden' value='all' name='pschp' />";
 3114:     $result .= "\n<input type='hidden' value='$symb' name='pssymb' />";
 3115:     $result .= "\n<input type='hidden' value='$paramlevel' name='parmlev' />";
 3116: 
 3117:     $result .= "<br /><br /><center><input type='submit' value='Finish Helper' /></center></form>\n";
 3118: 
 3119:     return $result;
 3120: }
 3121:     
 3122: sub overrideForm {
 3123:     return 1;
 3124: }
 3125: 
 3126: 1;
 3127: 
 3128: __END__
 3129: 

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