File:  [LON-CAPA] / loncom / homework / structuretags.pm
Revision 1.557: download - view: text, annotated - select for diffs
Fri Dec 22 01:55:28 2017 UTC (6 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Code in &start_problem() used to (a) display message depending on access
  status of a problem which uses slots, (b) display the web form for
  proctor validation, (c) check a user into a slot without proctor
  validation, is moved to three separate routines to faciltate re-use:
  &access_status_msg(), &checkin_prompt(), and &selfcheckin_resource().

    1: # The LearningOnline Network with CAPA 
    2: # definition of tags that give a structure to a document
    3: #
    4: # $Id: structuretags.pm,v 1.557 2017/12/22 01:55:28 raeburn 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: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::structuretags
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: 
   39: This is part of the LearningOnline Network with CAPA project
   40: described at http://www.lon-capa.org.
   41: 
   42: 
   43: =head1 NOTABLE SUBROUTINES
   44: 
   45: =over
   46: 
   47: =item 
   48: 
   49: =back
   50: 
   51: =cut
   52: 
   53: 
   54: package Apache::structuretags; 
   55: 
   56: use strict;
   57: use Apache::lonnet;
   58: use Apache::File();
   59: use Apache::lonmenu;
   60: use Apache::lonlocal;
   61: use Apache::lonxml;
   62: use Apache::londefdef;
   63: use Apache::lonenc();
   64: use Apache::loncommon();
   65: use Time::HiRes qw( gettimeofday tv_interval );
   66: use lib '/home/httpd/lib/perl/';
   67: use LONCAPA;
   68:  
   69: BEGIN {
   70:     &Apache::lonxml::register('Apache::structuretags',('block','languageblock','translated','instructorcomment','while','randomlist','problem','library','web','print','tex','part','preduedate','postanswerdate','solved','notsolved','problemtype','startpartmarker','startouttext','endpartmarker','endouttext','simpleeditbutton','definetag'));
   71: }
   72: 
   73: 
   74: #---------------------------------------------------------------------------------
   75: # 
   76: #  This section of code deals with hyphenation management.
   77: #  We must do three things:
   78: #  - keep track fo the desired languages to alter the header.
   79: #  - provide hyphenation selection as needed by each language that appears in the
   80: #    text.
   81: #  - Provide the header text needed to make available the desired hyphenations.
   82: #
   83: #
   84: 
   85: # Hash whose keys are the languages encountered in the document/resource.
   86: #
   87: 
   88: my %languages_required;
   89: ##
   90: #   Given a language selection as input returns a chunk of LaTeX that
   91: #   selects the required hyphenator.
   92: #
   93: #  @param language - the language being selected.
   94: #  @return string
   95: #  @retval The LaTeX needed to select the hyphenation appropriate to the language. 
   96: #   
   97: sub select_hyphenation {
   98:     my $language  = shift;
   99: 
  100:     $language = &Apache::loncommon::latexlanguage($language); # Translate -> latex language.
  101: 
  102:     # If there is no latex language there's not much we can do:
  103: 
  104:     if ($language) {
  105: 	&require_language($language);
  106: 	my $babel_hyphenation = "\\selectlanguage{$language}";
  107: 	
  108: 	return $babel_hyphenation;
  109:     } else {
  110: 	return '';
  111:     }
  112: }
  113: ##
  114: # Selects hyphenation based on the current problem metadata.
  115: # This requires that
  116: # - There is a language metadata item set for the problem.
  117: # - The language has a latex/babel hyphenation.
  118: #
  119: # @note: Uses &Apache::lonxml::request to locate the Uri associated with
  120: #        this problem.
  121: # @return string (possibly empty).
  122: # @retval If not empty an appropriate \selectlanguage{} directive.
  123: #
  124: sub select_metadata_hyphenation {
  125:     my $uri      = $Apache::lonxml::request->uri;
  126:     my $language = &Apache::lonnet::metadata($uri, 'language'); 
  127:     my $latex_language = &Apache::loncommon::latexhyphenation($language);
  128:     if ($latex_language) {
  129: 	return '\selectlanguage{'.$latex_language."}\n";
  130:     }
  131:     return '';			# no latex hyphenation or no lang metadata.
  132: }
  133: 
  134: 
  135: ##
  136: #  Clears the set of languages required by the document being rendered.
  137: #
  138: sub clear_required_languages {
  139:     %languages_required = ();
  140: }
  141: ##
  142: # Allows an external client of this module to register a need for a language:
  143: #
  144: # @param LaTeX language required:
  145: #
  146: sub require_language {
  147:     my $language = shift;
  148:     $languages_required{$language} = 1;
  149: }
  150: 
  151: ##
  152: # Provides the header for babel that indicates the languages
  153: # the document requires.
  154: # @return string
  155: # @retval \usepackage[lang1,lang2...]{babel}
  156: # @retval ''   if there are no languages_required.
  157: sub languages_header {
  158:     my $header    ='';
  159:     my @languages = (keys(%languages_required));
  160: 
  161:     # Only generate the header if there are languages:
  162: 
  163:     if (scalar @languages) {
  164: 	my $language_list = join(',', (@languages));
  165: 	$header  = '\usepackage['.$language_list."]{babel}\n";
  166:     }
  167:     return $header;
  168: }
  169: 
  170: #----------------------------------------------------------------------------------
  171: 
  172: sub start_web {
  173:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  174:     if ($target ne 'edit' && $target ne 'modified') {
  175: 	my $bodytext=&Apache::lonxml::get_all_text("/web",$parser,$style);
  176: 	if ($target eq 'web' || $target eq 'webgrade') {
  177: 	    return $bodytext;
  178: 	}
  179:     } elsif ($target eq "edit" ) {
  180: 	my $bodytext = 
  181: 	    &Apache::lonxml::get_all_text_unbalanced("/web",$parser);
  182: 	my $result = &Apache::edit::tag_start($target,$token);
  183: 	$result .= &Apache::edit::editfield($token->[1],$bodytext,'',80,1);
  184: 	return $result;
  185:     } elsif ( $target eq "modified" ) {
  186: 	return $token->[4].&Apache::edit::modifiedfield("/web",$parser);
  187:     }
  188:     return '';
  189: }
  190: 
  191: sub end_web {
  192:     return '';
  193: }
  194: 
  195: sub start_print {
  196:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  197:     if ($target ne 'edit' && $target ne 'modified') {
  198:         if ($target ne 'tex') {
  199:             my $skip = &Apache::lonxml::get_all_text("/print",$parser,$style);
  200:             &Apache::lonxml::debug("skipping ahead :$skip: $$parser[-1]");
  201:         }
  202:     } elsif ($target eq "edit") {
  203:         my $bodytext = &Apache::lonxml::get_all_text_unbalanced("/print",$parser);
  204:         my $result = &Apache::edit::tag_start($target,$token);
  205:         $result .= &Apache::edit::editfield($token->[1],$bodytext,'',80,1);
  206:         return $result;
  207:     } elsif ($target eq "modified") {
  208:         return $token->[4].&Apache::edit::modifiedfield("/print",$parser);
  209:     }
  210:     return '';
  211: }
  212: 
  213: sub end_print {
  214:     return '';
  215: }
  216: 
  217: sub start_tex {
  218:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  219:     my $result='';
  220:     if ($target ne 'edit' && $target ne 'modified') {
  221: 	my $bodytext=&Apache::lonxml::get_all_text("/tex",$parser,$style);
  222: 	if ($target eq 'tex') {
  223: 	    
  224: 	    # If inside a table, occurrences of \\ must be removed;
  225: 	    # else the table blows up.
  226: 
  227: 	    if (&Apache::londefdef::is_inside_of($tagstack, "table")) {
  228: 		$bodytext =~ s/\\\\//g;
  229: 	    }
  230: 	    return $bodytext.'{}';
  231: 	}
  232:     } elsif ($target eq "edit" ) {
  233: 	my $bodytext = 
  234: 	    &Apache::lonxml::get_all_text_unbalanced("/tex",$parser);
  235: 	my $result = &Apache::edit::tag_start($target,$token);
  236: 	$result .= &Apache::edit::editfield($token->[1],$bodytext,'',80,1);
  237: 	return $result;
  238:     } elsif ( $target eq "modified" ) {
  239: 	return $token->[4].&Apache::edit::modifiedfield("/tex",$parser);
  240:     }
  241:     return $result;;
  242: }
  243: 
  244: sub end_tex {
  245:     return '';
  246: }
  247: 
  248: sub homework_js {
  249:     my ($postsubmit,$timeout);
  250:     if (($env{'request.course.id'}) && ($env{'request.state'} ne 'construct')) {
  251:         my $crstype = &Apache::loncommon::course_type();
  252:         if ($crstype eq 'Community') {
  253:             $crstype = 'community';
  254:         } elsif ($crstype eq 'Placement') {
  255:             $crstype = 'placement'; 
  256:         } else {
  257:             if ($env{'course.'.$env{'request.course.id'}.'.internal.coursecode'}) {
  258:                 $crstype = 'official';
  259:             } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
  260:                 $crstype = 'textbook';
  261:             } else {
  262:                 $crstype = 'unofficial';
  263:             }
  264:         }
  265:         $postsubmit = $env{'course.'.$env{'request.course.id'}.'.internal.postsubmit'};
  266:         if ($postsubmit eq '') {
  267:             my %domdefs = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
  268:             $postsubmit = $domdefs{'postsubmit'};
  269:             unless ($postsubmit eq 'off') {
  270:                 $timeout = $domdefs{$crstype.'postsubtimeout'};
  271:             }
  272:         } elsif ($postsubmit eq '0') {
  273:             $postsubmit = 'off';
  274:         } elsif ($postsubmit eq '1') {
  275:             $postsubmit = 'on';
  276:             $timeout = $env{'course.'.$env{'request.course.id'}.'.internal.postsubtimeout'};
  277:             if ($timeout eq '') {
  278:                 my %domdefs = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
  279:                 $timeout = $domdefs{$crstype.'postsubtimeout'};
  280:             }
  281:         }
  282:         if ($timeout eq '') {
  283:             $timeout = 60;
  284:         }
  285:     } else {
  286:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
  287:         $postsubmit = $domdefs{'postsubmit'};
  288:         unless ($postsubmit eq 'off') {
  289:             $timeout = 60;
  290:         }
  291:     }
  292:     my $jstimeout = 0;
  293:     if ($timeout) {
  294:         $jstimeout = 1000 * $timeout;
  295:     }
  296:     return &Apache::loncommon::resize_textarea_js().
  297:                 &Apache::loncommon::colorfuleditor_js().
  298:            &setmode_javascript().
  299: 	<<"JS";
  300: <script type="text/javascript">
  301: // <![CDATA[
  302: function setSubmittedPart (part,prefix) {
  303:     if (typeof(prefix) == 'undefined') {
  304:         this.document.lonhomework.submitted.value="part_"+part;
  305:     } else {
  306:         for (var i=0;i<this.document.lonhomework.elements.length;i++) {
  307:             if (this.document.lonhomework.elements[i].name == prefix+'submitted') {
  308:                 this.document.lonhomework.elements[i].value="part_"+part;
  309:             }
  310:         }
  311:     }
  312: }
  313: 
  314: function disableAutoComplete (id) {
  315:     var field = document.getElementById(id);
  316:     if (field != null && field != undefined){
  317:         if ('autocomplete' in field) {
  318:             field.autocomplete = "off";
  319:         } else {
  320:             field.setAttribute("autocomplete", "off");
  321:         }
  322:     }
  323: }
  324: 
  325: function image_response_click (which, e) {
  326:     init_geometry();
  327:     if (!e) { e = window.event; } //IE
  328:     var input_element = document.lonhomework.elements[which];
  329:     var token_element = document.lonhomework.elements[which+'_token'];
  330:     var token = token_element.value;
  331:     var img_element   = document.getElementById(which+'_imageresponse');
  332:     var x= e.clientX-getX(img_element)+Geometry.getHorizontalScroll();
  333:     var y= e.clientY-getY(img_element)+Geometry.getVerticalScroll();
  334:     var click = x+':'+y;
  335:     input_element.value = click;
  336:     img_element.src = '/adm/randomlabel.png?token='+token+'&clickdata='+click;
  337: }
  338: 
  339: var submithandled = 0;
  340: var keypresshandled = 0;
  341: var postsubmit = '$postsubmit';
  342: 
  343: \$(document).ready(function(){
  344:   if (postsubmit != 'off') {    
  345:     \$(document).keypress(function(event){
  346:         var keycode = (event.keyCode ? event.keyCode : event.which);
  347:         if ((keycode == '13') && (keypresshandled == 0)) {
  348:             if ( \$( document.activeElement ).hasClass("LC_textline") ) {
  349:                 keypresshandled = 1;
  350:                 var idsArray = \$( document.activeElement ).attr("id").split(/HWVAL_/);
  351:                 if (idsArray.length) {
  352:                     event.preventDefault();
  353:                     var itemsArray = idsArray[1].split(/_/);
  354:                     var buttonId = idsArray[0]+'submit_'+itemsArray[0];
  355:                     \$("#"+buttonId).trigger("click");
  356:                 }
  357:             }
  358:         }
  359:     });
  360: 
  361:     \$(document).delegate('form :submit', 'click', function( event ) {
  362:         if ( \$( this ).hasClass( "LC_hwk_submit" ) ) {
  363:             var buttonId = this.id;
  364:             var timeout = $jstimeout;
  365:             if (submithandled == 0) {
  366:                 submithandled = 1;
  367:                 \$( "#msg_"+buttonId ).css({"display": "inline","background-color": "#87cefa",
  368:                                            "color": "black","padding": "2px"}) ;
  369:                 if (( \$(this.form).id == "LC_page" ) && (\$('input[name="all_submit"]').length )) {
  370:                     if (buttonId != "all_submit") {
  371:                         \$( ".LC_status_"+buttonId ).hide();
  372:                         if (( "#"+buttonId+"_pressed" ).length) {
  373:                             \$( "#"+buttonId+"_pressed" ).val( "1" );
  374:                         }
  375:                     }
  376:                 } else {
  377:                     \$( ".LC_status_"+buttonId ).hide();
  378:                 }
  379:                 \$(this.form).submit();
  380:                 \$( ".LC_hwk_submit" ).prop( "disabled", true);
  381:                 \$( ".LC_textline" ).prop( "readonly", "readonly");
  382:                 event.preventDefault();
  383: 
  384:                 if (timeout > 0) {
  385:                     setTimeout(function(){
  386:                                        \$( "#msg_"+buttonId ).css({"display": "none"});
  387:                                        if (( \$(this.form).id == "LC_page" ) && (\$('input[name="all_submit"]').length )) {
  388:                                            if (buttonId != "all_submit") {
  389:                                                if (( "#"+buttonId+"_pressed" ).length) {
  390:                                                    \$( "#"+buttonId+"_pressed" ).val( "" );
  391:                                                }
  392:                                            }
  393:                                        }
  394:                                        \$( ".LC_hwk_submit" ).prop( "disabled", false);
  395:                                        \$( ".LC_textline" ).prop( "readonly", false);
  396:                                        submithandled = 0;
  397:                                        keypresshandled = 0;
  398:                                      }, timeout);
  399:                 }
  400:                 return true;
  401:             }
  402:         }
  403:     });
  404:   }
  405: });
  406: 
  407: // ]]>
  408: </script>
  409: JS
  410: }
  411: 
  412: sub setmode_javascript {
  413:     return <<"ENDSCRIPT";
  414: <script type="text/javascript">
  415: // <![CDATA[
  416: function setmode(form,probmode) {
  417:     var initial = form.problemmode.value;
  418:     form.problemmode.value = probmode;
  419:     form.submit();
  420:     form.problemmode.value = initial;
  421: }
  422: // ]]>
  423: </script>
  424: ENDSCRIPT
  425: }
  426: 
  427: sub page_start {
  428:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$name,
  429: 	$extra_head)=@_;
  430:     my %found;
  431:     foreach my $taginside (@$tagstack) {
  432: 	foreach my $taglookedfor ('html','body','form') {
  433: 	    if ($taginside =~ /^$taglookedfor$/i) {$found{$taglookedfor} = 1;}
  434: 	}
  435:     }
  436: 
  437:     if ($target eq 'tex') {
  438: 	return
  439: 	    &Apache::londefdef::start_html($target,$token,$tagstack,
  440: 					   $parstack,$parser,$safeeval);
  441:     }
  442: 
  443:     $extra_head .= &homework_js().
  444:                    &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
  445:     if (&Apache::lonhtmlcommon::htmlareabrowser()) {
  446:         my %textarea_args;
  447:         if (($env{'request.state'} ne 'construct') ||
  448:             ($env{'environment.nocodemirror'})) {
  449:             %textarea_args = (
  450:                                 dragmath => 'math',
  451:                               );
  452:         }
  453:         $extra_head .= &Apache::lonhtmlcommon::htmlareaselectactive(\%textarea_args);
  454:     }
  455:     my $is_task = ($env{'request.uri'} =~ /\.task$/);
  456:     my ($needs_upload,$partlist);
  457:     my ($symb)= &Apache::lonnet::whichuser();
  458:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
  459:     if ($is_task) {
  460:         $extra_head .= &Apache::lonhtmlcommon::file_submissionchk_js();
  461:     } else {
  462:         if (&Apache::lonnet::EXT("resource.$Apache::inputtags::part.uploadedfiletypes") ne '') {
  463:             unless ($env{'request.state'} eq 'construct') {
  464:                 my $navmap = Apache::lonnavmaps::navmap->new();
  465:                 if (ref($navmap)) {
  466:                     my $mapres = $navmap->getResourceByUrl($map);
  467:                     my $is_page;
  468:                     if (ref($mapres)) {
  469:                         $is_page = $mapres->is_page();
  470:                     }
  471:                     unless ($is_page) {
  472:                         $needs_upload = 1;
  473:                     }
  474:                     if ((ref($tagstack) eq 'ARRAY') && ($tagstack->[-1] eq 'problem')) {
  475:                         my $res = $navmap->getBySymb($symb);
  476:                         if (ref($res)) {
  477:                             $partlist = $res->parts();
  478:                         }
  479:                     }
  480:                 }
  481:             }
  482:         } else {
  483:             unless ($env{'request.state'} eq 'construct') {
  484:                 my $navmap = Apache::lonnavmaps::navmap->new();
  485:                 if (ref($navmap)) {
  486:                     my $mapres = $navmap->getResourceByUrl($map);
  487:                     my $is_page;
  488:                     if (ref($mapres)) {
  489:                         $is_page = $mapres->is_page();
  490:                     }
  491:                     if ($is_page) {
  492:                         if ((ref($tagstack) eq 'ARRAY') && ($tagstack->[-1] eq 'problem')) {
  493:                             my $res = $navmap->getBySymb($symb);
  494:                             if (ref($res)) {
  495:                                 $partlist = $res->parts();
  496:                             }
  497:                         }
  498:                     } else {
  499:                         my $res = $navmap->getBySymb($symb);
  500:                         if (ref($res)) {
  501:                             $partlist = $res->parts();
  502:                             if (ref($partlist) eq 'ARRAY') {
  503:                                 foreach my $part (@{$partlist}) {
  504:                                     my @types = $res->responseType($part);
  505:                                     my @ids = $res->responseIds($part);
  506:                                     for (my $i=0; $i < scalar(@ids); $i++) {
  507:                                         if ($types[$i] eq 'essay') {
  508:                                             my $partid = $part.'_'.$ids[$i];
  509:                                             if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
  510:                                                 $needs_upload = 1;
  511:                                                 last;
  512:                                             }
  513:                                         }
  514:                                     }
  515:                                 }
  516:                             } 
  517:                         }
  518:                     }
  519:                 }
  520:             }
  521:         }
  522:         if ($needs_upload) {
  523:             $extra_head .= &Apache::lonhtmlcommon::file_submissionchk_js()
  524:                             .'<script type="text/javascript" 
  525:                                 src="/res/adm/includes/file_upload.js"></script>';
  526:         }
  527:     }
  528: 
  529:     my %body_args;
  530:     if (defined($found{'html'})) {
  531: 	$body_args{'skip_phases'}{'head'}=1;
  532:     } else {
  533: 	
  534: 	$extra_head .= &Apache::lonhtmlcommon::spellheader();
  535: 
  536: 	$extra_head .= &Apache::londefdef::generate_css_links();
  537: 
  538: 	if ($env{'request.state'} eq 'construct') {
  539: 	    $extra_head.=&Apache::edit::js_change_detection().
  540: 		"<script type=\"text/javascript\">\n".
  541: 		"if (typeof swmenu != 'undefined') {swmenu.currentURL=null;}\n".
  542: 		&Apache::loncommon::browser_and_searcher_javascript().
  543:                 "\n</script>\n";
  544:             if ($target eq 'edit') {
  545:                 $extra_head .= &Apache::edit::js_update_linknum();
  546:             }
  547: 	}
  548:     }
  549: 
  550:     my $pageheader = '';
  551:     if (defined($found{'body'})) {
  552: 	$body_args{'skip_phases'}{'body'}=1;
  553:     } elsif (!defined($found{'body'}) 
  554: 	     && $env{'request.state'} eq 'construct') {
  555: 	if ($target eq 'web' || $target eq 'edit') {
  556:             unless ($env{'form.inhibitmenu'} eq 'yes') {
  557:                 # Breadcrumbs for Authoring Space
  558:                 &Apache::lonhtmlcommon::clear_breadcrumbs();
  559:                 &Apache::lonhtmlcommon::add_breadcrumb({
  560:                     'text'  => 'Authoring Space',
  561:                     'href'  => &Apache::loncommon::authorspace($env{'request.uri'}),
  562:                 });
  563:                 # breadcrumbs (and tools) will be created 
  564:                 # in start_page->bodytag->innerregister
  565: 
  566: # FIXME Where are we?
  567: #                &Apache::lonhtmlcommon::add_breadcrumb({
  568: #                    'text'  => 'Problem Editing', # 'Problem Testing'
  569: #                    'href'  => '',
  570: #               });
  571:                 $pageheader = &Apache::loncommon::head_subbox(
  572:                                  &Apache::loncommon::CSTR_pageheader());
  573: 	    }
  574:         }
  575:     } elsif (!defined($found{'body'})) {
  576: 	my %add_entries;
  577: 	my $background=&Apache::lonxml::get_param('background',$parstack,
  578: 						  $safeeval);
  579: 	if ($background ne '' ) {
  580: 	    $add_entries{'background'} = $background;
  581: 	}
  582: 
  583: 	my $bgcolor=&Apache::lonxml::get_param('bgcolor',$parstack,
  584: 					       $safeeval);
  585:         if ($bgcolor eq '' ) { $bgcolor = '#FFFFFF'; }
  586: 
  587:         $body_args{'bgcolor'}        = $bgcolor;
  588:         # $body_args{'no_title'}       = 1;
  589:         $body_args{'force_register'} = 1;
  590:         $body_args{'add_entries'}    = \%add_entries;
  591:         if ( $env{'request.state'} eq   'construct') {
  592:             $body_args{'only_body'}  = 1;
  593:         } elsif ($target eq 'web') {
  594:             $body_args{'print_suppress'} = 1;
  595:         }
  596:     }
  597:     $body_args{'no_auto_mt_title'} = 1;
  598:     my $page_start = &Apache::loncommon::start_page($name,$extra_head,
  599: 						    \%body_args);
  600:     $page_start .= $pageheader;
  601:     if (!defined($found{'body'}) 
  602: 	&& $env{'request.state'} ne 'construct'
  603: 	&& ($target eq 'web' || $target eq 'webgrade')) {
  604: 
  605: 	my ($symb,undef,undef,undef,$publicuser)= &Apache::lonnet::whichuser();
  606:         if ($symb eq '' && !$publicuser) {
  607:             $page_start .= '<p class="LC_info">'
  608:                           .&mt('Browsing resource, all submissions are temporary.')
  609:                           .'</p>';
  610:         }
  611:     }
  612: 
  613:     if (!defined($found{'body'}) && $env{'request.state'} ne 'construct') {
  614: 	$page_start .= &Apache::lonxml::message_location();
  615:     }
  616:     my $form_tag_start;
  617:     if (!defined($found{'form'})) {
  618: 	$form_tag_start='<form name="lonhomework" enctype="multipart/form-data" method="post" action="';
  619: 	my $uri = &Apache::loncommon::inhibit_menu_check(
  620:                 &Apache::lonenc::check_encrypt($env{'request.uri'}));
  621:         $uri = &HTML::Entities::encode($uri,'<>&"');
  622: 	$form_tag_start.=$uri.'" ';
  623: 	if ($target eq 'edit') {
  624: 	    $form_tag_start.=&Apache::edit::form_change_detection();
  625: 	}
  626:         my ($symb,$courseid,$udom,$uname)=&Apache::lonnet::whichuser();
  627:         my ($path,$multiresp) = 
  628:             &Apache::loncommon::get_turnedin_filepath($symb,$uname,$udom);
  629:         if (($is_task) || ($needs_upload)) {
  630:             $form_tag_start .= ' onsubmit="return file_submission_check(this,'."'$path','$multiresp'".');"';
  631:         }
  632: 	$form_tag_start.='>'."\n";
  633: 
  634: 	if ($symb =~ /\S/) {
  635: 	    $symb=
  636: 		&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb));
  637: 	    $form_tag_start.=
  638: 		"\t".'<input type="hidden" name="symb" value="'.$symb.'" />'."\n";
  639: 	}
  640:     }
  641:     return ($page_start,$form_tag_start,$partlist);
  642: }
  643: 
  644: #use Time::HiRes();
  645: sub get_resource_name {
  646:     my ($parstack,$safeeval)=@_;
  647:     my $name;
  648:     if (defined($Apache::lonhomework::name)) {
  649: 	$name = $Apache::lonhomework::name;
  650:     } else {
  651: 	my ($symb)=&Apache::lonnet::whichuser();
  652: 	$name=&Apache::lonnet::gettitle($symb);
  653: 	if ($name eq '') {
  654: 	    $name=&Apache::lonnet::EXT('resource.title');
  655: 	    if ($name eq 'con_lost') { $name = ''; }
  656: 	}
  657: 	if ($name!~/\S+/) {
  658: 	    $name=$env{'request.uri'};
  659: 	    $name=~s-.*/([^/]+)$-$1-;
  660: 	}
  661: 	# The name has had html tags escaped:
  662:        
  663: 	$name=~s/&lt;/</gs;
  664: 	$name=~s/&gt;/>/gs;
  665: 
  666: 	$Apache::lonhomework::name=$name;
  667:     }
  668:     return $name;
  669: }
  670: 
  671: sub setup_rndseed {
  672:     my ($safeeval,$target,$probpartlist)=@_;
  673:     my ($symb)=&Apache::lonnet::whichuser();
  674:     my ($questiontype,$set_safespace,$rndseed);
  675:     if ($target eq 'analyze') {
  676:         $questiontype = $env{'form.grade_questiontype'};
  677:     }
  678:     unless (defined($questiontype)) {
  679:         $questiontype = $Apache::lonhomework::type;
  680:     }
  681:     if (($env{'request.state'} eq "construct")
  682:         || ($symb eq '')
  683:         || ($Apache::lonhomework::type eq 'practice')
  684:         || ($Apache::lonhomework::history{'resource.CODE'})
  685:         || (($env{'form.code_for_randomlist'}) && ($target eq 'analyze'))) {
  686: 	&Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  687: 						['rndseed']);
  688: 	$rndseed=$env{'form.rndseed'};
  689: 	if (!$rndseed) {
  690: 	    $rndseed=$Apache::lonhomework::history{'rndseed'};
  691: 	    if (!$rndseed) {
  692: 		$rndseed=time;
  693: 	    }
  694:             unless ($env{'form.code_for_randomlist'}) {
  695:                 $env{'form.rndseed'}=$rndseed;
  696:             }
  697: 	}
  698:         if (($env{'request.state'} eq "construct") && 
  699:             ($Apache::lonhomework::type eq 'randomizetry')) {
  700:             my $tries = $Apache::lonhomework::history{"resource.$Apache::inputtags::part.tries"};
  701:             if ($tries) {
  702:                 $rndseed += $tries;
  703:             }
  704:             $env{'form.'.$Apache::inputtags::part.'.rndseed'}=$rndseed;
  705:         }
  706: 	if ( ($env{'form.resetdata'} eq 'new_problem_variation'
  707: 	      && $env{'form.submitted'} eq 'yes')  ||
  708: 	    $env{'form.newrandomization'} eq &mt('New Randomization')) {
  709: 	    srand(time);
  710: 	    $rndseed=int(rand(2100000000));
  711: 	    $env{'form.rndseed'}=$rndseed;
  712: 	    delete($env{'form.resetdata'});
  713: 	    delete($env{'form.newrandomization'});
  714: 	}
  715:         $rndseed=~s/\,/\:/g;
  716:         $rndseed=~s/[^\w\d\:\-]//g;
  717: 	if (defined($rndseed)) {
  718:             my ($c1,$c2)=split(/\:/,$rndseed);
  719:             unless ($c2) { $c2=0; }
  720:             unless (($c1==int($c1)) && ($c2==int($c2))) {
  721: 	       $rndseed=join(':',&Apache::lonnet::digest($rndseed));
  722:             }
  723:         }
  724:         if (($env{'form.code_for_randomlist'}) && ($target eq 'analyze')) {
  725:             $env{'form.CODE'} = $env{'form.code_for_randomlist'};
  726:             $rndseed=&Apache::lonnet::rndseed();
  727:             undef($env{'form.CODE'});
  728:         } elsif ($Apache::lonhomework::history{'resource.CODE'}) {
  729: 	   $rndseed=&Apache::lonnet::rndseed();
  730: 	}
  731:         $set_safespace = 1;
  732:     } elsif ($questiontype eq 'randomizetry') {
  733:         if ($target eq 'analyze') {
  734:             if (defined($env{'form.grade_rndseed'})) {
  735:                 $rndseed = $env{'form.grade_rndseed'};
  736:             }
  737:         }
  738:         unless (($target eq 'analyze') && (defined($rndseed))) {
  739:             $rndseed=&Apache::lonnet::rndseed();
  740:             my $partfortries = $Apache::inputtags::part;
  741:             if (ref($probpartlist) eq 'ARRAY') {
  742:                 if ((@{$probpartlist} == 1) && ($probpartlist->[0] ne $Apache::inputtags::part)) {
  743:                     $partfortries = $probpartlist->[0];
  744:                 }
  745:             }
  746:             my $curr_try = $Apache::lonhomework::history{"resource.$partfortries.tries"};
  747:             if ($Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
  748:                 $curr_try ++;
  749:             }
  750:             if ($rndseed =~/^(\d+)[,:](\d+)$/) {
  751:                 $rndseed = $1;
  752:             }
  753:             if ($curr_try) {
  754:                 my $reqtries = &Apache::lonnet::EXT("resource.$partfortries.randomizeontries");
  755:                 if (($reqtries =~ /^\d+$/) && ($reqtries > 1)) {
  756:                     my $inc = int(($curr_try-1)/$reqtries);
  757:                     $rndseed += $inc;
  758:                 } else {
  759:                     $rndseed += $curr_try;
  760:                 }
  761:             }
  762:         }
  763:         $set_safespace = 1;
  764:         if ($target eq 'grade') {
  765:             $Apache::lonhomework::rawrndseed = $rndseed;
  766:         }
  767:     }
  768:     if ($set_safespace) {
  769:         if ($safeeval) {
  770:             &Apache::lonxml::debug("Setting rndseed to $rndseed");
  771:             &Apache::run::run('$external::randomseed="'.$rndseed.'";',$safeeval);
  772:         }
  773:     }
  774:     unless (($env{'request.state'} eq "construct") || ($symb eq '')) {
  775:         $env{'form.'.$Apache::inputtags::part.'.rndseed'}=$rndseed;
  776:     }
  777:     return $rndseed;
  778: }
  779: 
  780: sub remember_problem_state {
  781:     return '
  782:        <input type="hidden" name="problemstate" value="'.$env{'form.problemstate'}.'" />
  783:        <input type="hidden" name="problemtype" value="'.$env{'form.problemtype'}.'" />
  784:        <input type="hidden" name="problemstatus" value="'.$env{'form.problemstatus'}.'" />';
  785: }
  786: 
  787: sub problem_edit_action_button {
  788:     my ($name,$action,$accesskey,$text,$flag)=@_;
  789:     my $actionscript="setmode(this.form,'$action')";
  790:     return "\n<input type='button' name='$name' accesskey='$accesskey' value='".&mt($text)."'".
  791:            ($flag?&Apache::edit::submit_ask_anyway($actionscript):&Apache::edit::submit_dont_ask($actionscript))." />";
  792: }
  793: 
  794: sub problem_edit_buttons {
  795:    my ($mode)=@_;
  796: # Buttons that save
  797:    my $result = '<div style="float:right">';
  798:    if ($mode eq 'editxml') {
  799:        $result.=&problem_edit_action_button('subsaveedit','saveeditxml','s','Save and EditXML');
  800:        $result.=&problem_edit_action_button('subsaveview','saveviewxml','v','Save and View');
  801:    } else {
  802:        $result.=&problem_edit_action_button('subsaveedit','saveedit','s','Save and Edit');
  803:        $result.=&problem_edit_action_button('subsaveview','saveview','v','Save and View');
  804:    }
  805:    $result.="\n</div>\n";
  806: # Buttons that do not save
  807:    $result .= '<div>'.
  808:               &problem_edit_action_button('subdiscview','discard','d','Discard Edits and View',1);
  809:    if ($mode eq 'editxml') {
  810:        $result.=&problem_edit_action_button('subedit','edit','e','Edit',1);
  811:        $result.=&problem_edit_action_button('subundo','undoxml','u','Undo',1);
  812:        if ($env{'environment.nocodemirror'}) {
  813:            $result.=&Apache::lonhtmlcommon::dragmath_button("LC_editxmltext",1);
  814:        }
  815:    } else {
  816:        $result.=&problem_edit_action_button('subeditxml','editxml','x','EditXML',1);
  817:        $result.=&problem_edit_action_button('subundo','undo','u','Undo',1);
  818:    }
  819:    $result.="\n</div>";
  820:    return $result;
  821: }
  822: 
  823: sub problem_edit_header {
  824:     my ($mode)=@_;
  825:     my $return = '<input type="hidden" name="submitted" value="edit" />'.
  826: 	&remember_problem_state('edit').'
  827:         <div class="LC_edit_problem_header">
  828:         <div class="LC_edit_problem_header_title">
  829:         '.&mt('Problem Editing').$mode.&Apache::loncommon::help_open_menu('Problem Editing','Problem_Editor_XML_Index',5,'Authoring').'
  830:         </div><div class="LC_edit_actionbar" id="actionbar">'.
  831:         '<input type="hidden" name="problemmode" value="saveedit" />'.
  832:         &problem_edit_buttons();
  833: 
  834:     $return .= '</div></div>' . &Apache::lonxml::message_location();
  835:     $return .= '<link rel="stylesheet" href="/adm/codemirror/codemirror-combined.css" />
  836:     <script type="text/javascript" src="/adm/codemirror/codemirror-compressed-colorful.js"></script>';
  837: 
  838:     $return .= '<script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
  839:         <script type="text/javascript">
  840:             // unless internet explorer
  841:             if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
  842:                 $(document).ready(
  843:                     function() {
  844:                         $(\'.LC_edit_actionbar\').scrollToFixed(
  845:                             {
  846:                                 fixed: function(){
  847:                                     //$(this).find(\'.LC_edit_actionbar\').css(\'height\', \'31px\');
  848:                                     $(this).find(\'.LC_edit_actionbar\');
  849:                                 }
  850:                             }
  851:                         );
  852:                     }
  853:                 );
  854:             }
  855:         </script>
  856:         <table id="LC_edit_problem_colorful" border="0" width="100%"><tr><td bgcolor="#F8F8F8">';
  857:     return $return;
  858: }
  859: 
  860: sub problem_edit_footer {
  861:     my $resource = $env{'request.ambiguous'};
  862:     return '</td></tr></table><br />
  863: <div class="LC_edit_problem_footer">
  864:   <hr />'.
  865: &problem_edit_buttons().'
  866:   <hr style="clear:both;" />
  867:   <script type="text/javascript">
  868:       restoreState("'.$resource.'");
  869:       restoreScrollPosition("'.$resource.'");
  870:   </script>
  871: </div>
  872: '.
  873:     "\n</form>\n".&Apache::loncommon::end_page();
  874: }
  875: 
  876: sub option {
  877:     my ($value,$name) = @_;
  878:     my $result ="<option value='".$value."' ";
  879:     if ($env{'form.'.$name} eq $value) {
  880: 	$result.=" selected='on' ";
  881:     }
  882:     $result.='>';
  883:     return $result;
  884: }
  885: 
  886: sub problem_web_to_edit_header {
  887:     my ($rndseed)=@_;
  888:     my $result .= '<div class="LC_edit_problem_header">';
  889: 
  890:     if (!$Apache::lonhomework::parsing_a_task) {
  891: 	$result .= 
  892: 	    '<div class="LC_edit_problem_header_title">'.
  893: 	    &mt('Problem Testing').
  894: 	    &Apache::loncommon::help_open_topic('Problem_Editor_Testing_Area').
  895: 	    '</div>';
  896:     } else {
  897: 	$result .= 
  898: 	    '<div class="LC_edit_problem_header_title">'.
  899: 	    &mt('Task Testing').
  900: 	    '</div>';
  901:     }
  902:     
  903:     my $show_all_foils_text = 
  904: 	($Apache::lonhomework::parsing_a_task) ?
  905: 	&mt('Show All Instances')
  906: 	: &mt('Show All Foils');
  907: 
  908:     my $show_all= '<span class="LC_nobreak"><label for="showallfoils">'
  909:                  .'<input type="checkbox" name="showallfoils"';
  910:     if (defined($env{'form.showallfoils'})) { $show_all.=' checked="checked"'; }
  911:     $show_all.= ' /> '.$show_all_foils_text
  912:                .'</label></span>';
  913: 
  914: 
  915: 
  916:     $result .= '<div class="LC_edit_problem_header_status_row">';
  917:     if (!$Apache::lonhomework::parsing_a_task) {
  918: 	$result.="
  919: <div class='LC_edit_problem_header_row1'>
  920: <span class=\"LC_nobreak\">
  921: ".&mt("Problem Status:")."
  922: <select name='problemstate'>
  923:   <option value=''></option>
  924:   ".&option('CLOSED'               ,'problemstate').&mt("Closed")."</option>
  925:   ".&option('CAN_ANSWER'           ,'problemstate').&mt("Answerable")."</option>
  926:   ".&option('CANNOT_ANSWER_tries'  ,'problemstate').&mt("Open with full tries")."</option>
  927:   ".&option('CANNOT_ANSWER_correct','problemstate').&mt("Open and correct")."</option>
  928:   ".&option('SHOW_ANSWER'          ,'problemstate').&mt("Show Answer")."</option>
  929: </select>
  930: </span>
  931: <span class=\"LC_nobreak\">
  932: ".&mt("Problem Type:")."
  933: <select name='problemtype'>
  934:   <option value=''></option>
  935:   ".&option('exam'   ,'problemtype').&mt("Bubblesheet Exam Problem")."</option>
  936:   ".&option('problem','problemtype').&mt("Homework Problem")."</option>
  937:   ".&option('survey' ,'problemtype').&mt("Survey Question")."</option>
  938:   ".&option('surveycred' ,'problemtype').&mt("Survey Question (with credit)")."</option>
  939:   ".&option('anonsurvey' ,'problemtype').&mt("Anonymous Survey Question")."</option>
  940:   ".&option('anonsurveycred' ,'problemtype').&mt("Anonymous Survey Question (with credit)")."</option>
  941:   ".&option('practice' ,'problemtype').&mt("Practice Problem")."</option>
  942:   ".&option('randomizetry' ,'problemtype').&mt("New Randomization Each Try")."</option>
  943: </select>
  944: </span>
  945: $show_all
  946: </div>
  947: <div class='LC_edit_problem_header_row2'>
  948: <span class=\"LC_nobreak\">
  949: ".&mt("Feedback Mode:")."
  950: <select name='problemstatus'>
  951:   <option value=''></option>
  952:   ".&option('yes','problemstatus').&mt("Show Feedback")."</option>
  953:   ".&option('no', 'problemstatus').&mt("Don't Show Incorrect/Correct Feedback")."</option>
  954:   ".&option('no_feedback_ever', 'problemstatus').&mt("Don't Show Any Feedback")."</option>
  955: </select>
  956: </span>
  957: ";
  958: 
  959:     } elsif ($Apache::lonhomework::parsing_a_task) {
  960: 	$result.="
  961: <div class='LC_edit_problem_header_row1'>
  962: <span class=\"LC_nobreak\">
  963: ".&mt("Problem Status:")."
  964: <select name='problemstate'>
  965:   <option value=''></option>
  966:   ".&option('CLOSED'               ,'problemstate').&mt("Closed")."</option>
  967:   ".&option('CAN_ANSWER'           ,'problemstate').&mt("Answerable")."</option>
  968:   ".&option('WEB_GRADE'            ,'problemstate').&mt("Criteria Grading")."</option>
  969:   ".&option('SHOW_ANSWER'          ,'problemstate').&mt("Show Feedback")."</option>
  970: </select>
  971: </span>
  972: $show_all
  973: ";
  974:     }
  975:     $result.='
  976:        <span class="LC_nobreak">
  977:        '.&mt('Apply style file: ').'
  978:          <input type="text" name="style_file" value="'.&HTML::Entities::encode($env{'construct.style'},'"<>&').'" />
  979:          <a href="javascript:openbrowser(\'lonhomework\',\'style_file\',\'sty\')">'.&mt('Select').'</a>
  980:        </span>
  981:      </div>
  982:      <div class="LC_edit_problem_header_row1">'.
  983:        &Apache::lonxml::renderingoptions().'
  984:      </div>
  985:      <input type="submit" name="changeproblemmode" value="'.&mt("Change View").'" />
  986:      <input type="submit" name="clear_style_file" accesskey="d" value="'.&mt('Show Default View').'" />
  987:      <button type="submit" name="resetdata" accesskey="r" value="reset_submissions">
  988:      '.&mt('Reset Submissions').'</button>
  989:    </div>
  990:    <hr />
  991:    <div class="LC_edit_problem_header_randomize_row">
  992:      <input type="submit" name="newrandomization" accesskey="a" value="'.&mt('New Randomization').'" />
  993:      <input type="submit" name="changerandseed" value="'.&mt('Change Random Seed To:').'" />
  994:      <input type="text" name="rndseed" size="24" value="'.
  995: 	       $rndseed.'"
  996:              onchange="javascript:document.lonhomework.changerandseed.click()" />';
  997: 
  998:     if (!$Apache::lonhomework::parsing_a_task) {
  999: 	my $numtoanalyze=$env{'form.numtoanalyze'};
 1000: 	if (!$numtoanalyze) { $numtoanalyze=20; }
 1001: 	$result .= '<span class="LC_nobreak">'.
 1002: 	    &mt('[_1] for [_2] versions.',
 1003: 		'<input type="button" name="submitmode" value="'.&mt('Calculate answers').'" '.
 1004:                 'onclick="javascript:setmode(this.form,'."'calcanswers'".')" />'
 1005:                ,'<input type="text" name="numtoanalyze" value="'.
 1006: 		$numtoanalyze.'" size="5" />').
 1007: 		&Apache::loncommon::help_open_topic("Analyze_Problem",'',undef,undef,300).
 1008: 		'</span>';
 1009: 						    
 1010:     }
 1011: 
 1012:     $result.='
 1013:    </div>
 1014:    <hr />
 1015:    <div>';
 1016:     $result.='<input type="hidden" name="problemmode" value="view" />';
 1017:     $result .= '<input type="button" name="submitmode" accesskey="e" value="'.&mt('Edit').'" '.
 1018:                'onclick="javascript:setmode(this.form,'."'edit'".')" />';
 1019:     $result .= '<input type="button" name="submitmode" accesskey="x" value="'.&mt('EditXML').'" '.
 1020:                'onclick="javascript:setmode(this.form,'."'editxml'".')" />';
 1021:     if ($env{'browser.type'} ne 'explorer' || $env{'browser.version'} > 9) {
 1022:         my $uri = $env{'request.uri'};
 1023:         my $daxeurl = '/daxepage'.$uri;
 1024:         $result .= '<input type="button" value="'.&mt('Edit with Daxe').'" '.
 1025:                   'onclick="window.open(\''.$daxeurl.'\',\'_blank\');" />';
 1026:     }
 1027:     $result.='
 1028:    </div>
 1029:    <hr />
 1030:    '.&Apache::lonxml::message_location().'
 1031: </div>';
 1032:     return $result;
 1033: }
 1034: 
 1035: sub initialize_storage {
 1036:     my ($given_symb) = @_;
 1037:     undef(%Apache::lonhomework::results);
 1038:     undef(%Apache::lonhomework::history);
 1039:     my ($symb,$courseid,$domain,$name) = 
 1040: 	&Apache::lonnet::whichuser($given_symb);
 1041:     
 1042:     # anonymous users (CODEd exams) have no data
 1043:     if ($name eq 'anonymous' 
 1044: 	&& !defined($domain)) {
 1045: 	return;
 1046:     }
 1047: 
 1048:     if ($env{'request.state'} eq 'construct' 
 1049: 	|| $symb eq ''
 1050: 	|| $Apache::lonhomework::type eq 'practice') {
 1051: 	
 1052: 	my $namespace = $symb || $env{'request.uri'};
 1053: 	if ($env{'form.resetdata'} eq 'reset_submissions' ||
 1054: 	    ($env{'form.resetdata'} eq 'new_problem_variation'
 1055: 	     && $env{'form.submitted'} eq 'yes') ||
 1056: 	    $env{'form.newrandomization'} eq &mt('New Randomization')) {
 1057: 	    &Apache::lonnet::tmpreset($namespace,'',$domain,$name);
 1058: 	    &Apache::lonxml::debug("Attempt reset");
 1059: 	}
 1060: 	%Apache::lonhomework::history=
 1061: 	    &Apache::lonnet::tmprestore($namespace,'',$domain,$name);
 1062: 	my ($temp)=keys(%Apache::lonhomework::history) ;
 1063: 	&Apache::lonxml::debug("Return message of $temp");
 1064:     } else {
 1065: 	%Apache::lonhomework::history=
 1066: 	    &Apache::lonnet::restore($symb,$courseid,$domain,$name);
 1067:     }
 1068: 
 1069:     #ignore error conditions
 1070:     my ($temp)=keys(%Apache::lonhomework::history);
 1071:     if ($temp =~ m/^error:.*/) { %Apache::lonhomework::history=(); }
 1072: }
 1073: 
 1074: =pod
 1075: 
 1076: =item finalize_storage()
 1077: 
 1078: 	Stores away the result hash to a student's environment;
 1079: 	checks form.grade_ for specific values, otherwise stores
 1080: 	to the running user's environment.
 1081: 
 1082:         &check_correctness_changes() is called in two circumstances
 1083:         in which the results hash is to be stored permanently, for
 1084:         grading triggered by a student's submission, where feedback on
 1085:         correctness is to be provided to the student. 
 1086: 
 1087:         1. Immediately prior to storing the results hash
 1088: 
 1089:         To handle the case where a student's submission (and award) were 
 1090:         stored after history was retrieved in &initialize_storage(), e.g.,
 1091:         if a student submitted answers in quick succession (e.g., from 
 1092:         multiple tabs).  &Apache::inputtags::hidealldata() is called for
 1093:         any parts with out-of-order storage (i.e., correct then incorrect,
 1094:         where awarded >= 1 when correct).
 1095: 
 1096:         2. Immediately after storing the results hash
 1097: 
 1098:         To handle the case where lond on the student's homeserver returns
 1099:         delay:N -- where N is the number of transactions between the last
 1100:         retrieved in &initialize_storage() and the last stored immediately
 1101:         before permanent storage of the current transaction via 
 1102:         lond::store_handler().  &Apache::grades::makehidden() is called  
 1103:         for any parts with out-of-order storage (i.e., correct then incorrect,
 1104:         where awarded >= 1 when correct).
 1105: 
 1106: 	Will call &store_aggregates() to increment totals for attempts, 
 1107:         students, and corrects, if running user has student role.
 1108: 
 1109: =cut
 1110: 
 1111: 
 1112: sub finalize_storage {
 1113:     my ($given_symb) = @_;
 1114:     my $result;
 1115:     if (%Apache::lonhomework::results) {
 1116: 	my @remove = grep(/^INTERNAL_/,keys(%Apache::lonhomework::results));
 1117: 	delete(@Apache::lonhomework::results{@remove});
 1118: 	my ($symb,$courseid,$domain,$name) = 
 1119: 	    &Apache::lonnet::whichuser($given_symb);
 1120: 	if ($env{'request.state'} eq 'construct' 
 1121: 	    || $symb eq ''
 1122: 	    || $Apache::lonhomework::type eq 'practice') {
 1123: 	    my $namespace = $symb || $env{'request.uri'};
 1124: 	    $Apache::lonhomework::results{'rndseed'}=$env{'form.rndseed'};
 1125: 	    $result=&Apache::lonnet::tmpstore(\%Apache::lonhomework::results,
 1126: 					      $namespace,'',$domain,$name);
 1127: 	    &Apache::lonxml::debug('Construct Store return message:'.$result);
 1128: 	} else {
 1129:             my ($laststore,$checkedparts,@parts,%postcorrect);
 1130:             if (($env{'user.name'} eq $name) && ($env{'user.domain'} eq $domain) &&
 1131:                 (!$Apache::lonhomework::scantronmode) && (!defined($env{'form.grade_symb'})) &&
 1132:                 (!defined($env{'form.grade_courseid'}))) {
 1133:                 if ($Apache::lonhomework::history{'version'}) {
 1134:                     $laststore = $Apache::lonhomework::history{'version'}.'='.
 1135:                                  $Apache::lonhomework::history{'timestamp'};
 1136:                 } else {
 1137:                     $laststore = '0=0';
 1138:                 }
 1139:                 my %record = &Apache::lonnet::restore($symb,$courseid,$domain,$name);
 1140:                 if ($record{'version'}) {
 1141:                     my ($newversion,$oldversion,$oldtimestamp);
 1142:                     if ($Apache::lonhomework::history{'version'}) {
 1143:                         $oldversion = $Apache::lonhomework::history{'version'};
 1144:                         $oldtimestamp = $Apache::lonhomework::history{'timestamp'};
 1145:                     } else {
 1146:                         $oldversion = 0;
 1147:                         $oldtimestamp = 0;
 1148:                     }
 1149:                     if ($record{'version'} > $oldversion) {
 1150:                         if ($record{'timestamp'} >= $oldtimestamp) {
 1151:                             $laststore = $record{'version'}.'='.$record{'timestamp'};
 1152:                             $newversion = $record{'version'} + 1;
 1153:                             $checkedparts = 1;
 1154:                             foreach my $key (keys(%Apache::lonhomework::results)) {
 1155:                                 if ($key =~ /^resource\.([^\.]+)\.solved$/) {
 1156:                                     my $part = $1;
 1157:                                     if ($Apache::lonhomework::results{$key} eq 'incorrect_attempted') {
 1158:                                         push(@parts,$part);
 1159:                                     }
 1160:                                 }
 1161:                             }
 1162:                             if (@parts) {
 1163:                                 my @parts_to_hide = &check_correctness_changes($symb,$courseid,$domain,$name,
 1164:                                                                                \%record,\@parts,$newversion,
 1165:                                                                                $oldversion);
 1166:                                 if (@parts_to_hide) {
 1167:                                     foreach my $part (@parts_to_hide) {
 1168:                                         $postcorrect{$part} = 1;
 1169:                                         &Apache::inputtags::hidealldata($part);
 1170:                                     }
 1171:                                 }
 1172:                             }
 1173:                         }
 1174:                     }
 1175:                 }
 1176:             }
 1177: 	    $result=&Apache::lonnet::cstore(\%Apache::lonhomework::results,
 1178: 					    $symb,$courseid,$domain,$name,$laststore);
 1179:             if ($result =~ /^delay\:(\d+)$/) {
 1180:                 my $numtrans = $1;
 1181:                 my ($oldversion) = split(/=/,$laststore);
 1182:                 if ($numtrans) {
 1183:                     my $newversion = $oldversion + 1 + $numtrans;
 1184:                     my @possparts;
 1185:                     if ($checkedparts) {
 1186:                         foreach my $part (@parts) {
 1187:                             unless ($postcorrect{$part}) {
 1188:                                 push(@possparts,$part);
 1189:                             }
 1190:                         }
 1191:                     } else {
 1192:                         foreach my $key (keys(%Apache::lonhomework::results)) {
 1193:                             if ($key =~ /^resource\.([^\.]+)\.solved$/) {
 1194:                                 my $part = $1;
 1195:                                 unless ($postcorrect{$part}) {
 1196:                                     if ($Apache::lonhomework::results{$key} eq 'incorrect_attempted') {
 1197:                                         push(@possparts,$part);
 1198:                                     }
 1199:                                 }
 1200:                             }
 1201:                         }
 1202:                     }
 1203:                     if (@possparts) {
 1204:                         my %newrecord = &Apache::lonnet::restore($symb,$courseid,$domain,$name);
 1205:                         my @parts_to_hide = &check_correctness_changes($symb,$courseid,$domain,$name,
 1206:                                                                        \%newrecord,\@possparts,$newversion,
 1207:                                                                        $oldversion);
 1208:                         if (@parts_to_hide) {
 1209:                             my $partslist = join(',',@parts_to_hide);
 1210:                             &Apache::grades::makehidden($newversion,$partslist,\%newrecord,$symb,$domain,$name,1);
 1211:                         }
 1212:                     }
 1213:                 }
 1214:             }
 1215: 	    &Apache::lonxml::debug('Store return message:'.$result);
 1216:             &store_aggregates($symb,$courseid);
 1217: 	}
 1218:     } else {
 1219: 	&Apache::lonxml::debug('Nothing to store');
 1220:     }
 1221:     return $result;
 1222: }
 1223: 
 1224: =pod
 1225: 
 1226: =item check_correctness_changes()
 1227: 
 1228:         For all parts for which current results contain a solved status
 1229:         of "incorrect_attempted", check if there was a transaction in which  
 1230:         solved was set to "correct_by_student" in the time since the last 
 1231:         transaction (retrieved when &initialize_storage() was called i.e., 
 1232:         when &start_problem() was called), unless:
 1233:         (a) questiontype parameter is set to survey or anonymous survey (+/- credit)
 1234:         (b) problemstatus is set to no or no_feedback_ever
 1235:         If such a transaction exists, and did not occur after "reset status" 
 1236:         by a user with grading privileges, then the current transaction is an
 1237:         example of an out-of-order transaction (i.e., incorrect occurring after
 1238:         correct).  Accordingly, the current transaction should be hidden.
 1239: 
 1240: =cut
 1241: 
 1242: 
 1243: sub check_correctness_changes {
 1244:     my ($symb,$courseid,$domain,$name,$record,$parts,$newversion,$oldversion) = @_;
 1245:     my @parts_to_hide;
 1246:     unless ((ref($record) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 1247:         return @parts_to_hide;
 1248:     }
 1249:     if (@{$parts}) {
 1250:         my $usec;
 1251:         if (($env{'user.name'} eq $name) && ($env{'user.domain'} eq $domain) &&
 1252:             ($env{'request.course.id'} eq $courseid)) {
 1253:             $usec = $env{'request.course.sec'};
 1254:         } else {
 1255:             $usec = &Apache::lonnet::getsection($domain,$name,$courseid);
 1256:         }
 1257:         foreach my $id (@{$parts}) {
 1258:             next if (($Apache::lonhomework::results{'resource.'.$id.'.type'} =~ /survey/) ||
 1259:                      (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 1260:                                            $domain,$name,$usec,undef,$courseid) =~ /^no/));
 1261:             my $reset;
 1262:             for (my $i=$newversion-1; $i>=$oldversion; $i--) {
 1263:                 if (($record->{$i.':resource.'.$id.'.regrader'}) &&
 1264:                     ($record->{$i.':resource.'.$id.'.tries'} eq '') &&
 1265:                     ($record->{$i.':resource.'.$id.'.award'} eq '')) {
 1266:                     $reset = 1;
 1267:                 } elsif (($record->{$i.":resource.$id.solved"} eq 'correct_by_student') &&
 1268:                          ($record->{$i.":resource.$id.awarded"} >= 1)) {
 1269:                     unless ($reset) {
 1270:                         push(@parts_to_hide,$id);
 1271:                         last;
 1272:                     }
 1273:                 }
 1274:             }
 1275:         }
 1276:     }
 1277:     return @parts_to_hide;
 1278: }
 1279: 
 1280: =pod
 1281: 
 1282: item store_aggregates()
 1283: 
 1284: 	Sends hash of values to be incremented in nohist_resourcetracker.db
 1285: 	for the course. Increments total number of attempts, unique students 
 1286: 	and corrects for each part for an instance of a problem, as appropriate.
 1287: 	
 1288: =cut
 1289: 
 1290: sub store_aggregates {
 1291:     my ($symb,$courseid) = @_;
 1292:     my (%aggregate,%anoncounter,%randtrycounter);
 1293:     my @parts;
 1294:     my $cdomain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1295:     my $cname = $env{'course.'.$env{'request.course.id'}.'.num'};
 1296:     foreach my $key (keys(%Apache::lonhomework::results)) {
 1297:         if ($key =~ /resource\.([^\.]+)\.tries/) {
 1298:             push(@parts, $1);
 1299:         }
 1300:     }
 1301:     foreach my $part (@parts) {
 1302:         if ($env{'request.role'} =~/^st/) {
 1303:             if ($Apache::lonhomework::results{'resource.'.$part.'.award'}
 1304: 	        eq 'APPROX_ANS' ||
 1305: 	        $Apache::lonhomework::results{'resource.'.$part.'.award'}
 1306: 	        eq 'EXACT_ANS') {
 1307:                 $aggregate{$symb."\0".$part."\0correct"} = 1;
 1308:             }
 1309:             if ($Apache::lonhomework::results{'resource.'.$part.'.tries'} == 1) {
 1310:                 $aggregate{$symb."\0".$part."\0users"} = 1;
 1311:             } else {
 1312:                 my (undef,$last_reset) = &Apache::grades::get_last_resets($symb,$env{'request.course.id'},[$part]); 
 1313:                 if ($last_reset) {
 1314:                     if (&Apache::grades::get_num_tries(\%Apache::lonhomework::history,$last_reset,$part) == 0) {
 1315:                         $aggregate{$symb."\0".$part."\0users"} = 1;
 1316:                     }
 1317:                 }
 1318:             }
 1319:             $aggregate{$symb."\0".$part."\0attempts"} = 1;
 1320:         }
 1321:         if (($Apache::lonhomework::results{'resource.'.$part.'.type'} eq 'anonsurvey') || 
 1322:             ($Apache::lonhomework::results{'resource.'.$part.'.type'} eq 'anonsurveycred') ||
 1323:             ($Apache::lonhomework::results{'resource.'.$part.'.type'} eq 'randomizetry')) {
 1324:             if ($Apache::lonhomework::results{'resource.'.$part.'.type'} eq 'randomizetry') {
 1325:                 $randtrycounter{$symb."\0".$part} = 1;
 1326:             } else {
 1327:                 $anoncounter{$symb."\0".$part} = 1;
 1328:             }
 1329:             my $needsrelease = $Apache::lonnet::needsrelease{'parameter:type:'.$Apache::lonhomework::results{'resource.'.$part.'.type'}.'::'};
 1330:             if ($needsrelease) {
 1331:                 my $curr_required = $env{'course.'.$env{'request.course.id'}.'.internal.releaserequired'};
 1332:                 if ($curr_required eq '') {
 1333:                     &Apache::lonnet::update_released_required($needsrelease);
 1334:                 } else {
 1335:                     my ($currmajor,$currminor) = split(/\./,$curr_required);
 1336:                     my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 1337:                     if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 1338:                         &Apache::lonnet::update_released_required($needsrelease);
 1339:                     }
 1340:                 }
 1341:             }
 1342:         }
 1343:     }
 1344:     if (keys(%aggregate) > 0) {
 1345: 	&Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 1346:                             $cdomain,$cname);
 1347:     }
 1348:     if (keys(%anoncounter) > 0) {
 1349:         &Apache::lonnet::cput('nohist_anonsurveys',\%anoncounter,
 1350:                               $cdomain,$cname);
 1351:     }
 1352:     if (keys(%randtrycounter) > 0) {
 1353:         &Apache::lonnet::cput('nohist_randomizetry',\%randtrycounter,
 1354:                               $cdomain,$cname);
 1355:     }
 1356: }
 1357: 
 1358: sub access_status_msg {
 1359:     my ($mode,$status,$symb,$target,$ipused,$accessmsg) = @_;
 1360:     my $msg;
 1361:     if ($target eq 'web') {
 1362:         if ($status eq 'UNAVAILABLE') {
 1363:             $msg.='<p class="LC_error">'.&mt('Unable to determine if this resource is open due to network problems. Please try again later.').'</p>';
 1364:         } elsif ($status eq 'NOT_IN_A_SLOT') {
 1365:             $msg.='<p class="LC_warning">'.&mt('You are not currently signed up to work at this time and/or place.').'</p>';
 1366:         } elsif (($status eq 'RESERVABLE') || ($status eq 'RESERVABLE_LATER') ||
 1367:                  ($status eq 'NOTRESERVABLE')) {
 1368:             $msg.='<p class="LC_warning">'.&mt('Access requires reservation to work at specific time/place.').'</p>';
 1369:         } elsif ($status ne 'NOT_YET_VIEWED') {
 1370:             $msg.='<p class="LC_warning">'.&mt('Not open to be viewed').'</p>';
 1371:         }
 1372:         if ($status eq 'CLOSED' || $status eq 'INVALID_ACCESS') {
 1373:             $msg.=&mt('The problem ').$accessmsg;
 1374:         } elsif ($status eq 'UNCHECKEDOUT') {
 1375:             $msg.=&checkout_msg();
 1376:         } elsif ($status eq 'NOT_YET_VIEWED') {
 1377:             $msg.=&firstaccess_msg($accessmsg,$symb);
 1378:         } elsif ($status eq 'NOT_IN_A_SLOT') {
 1379:             $msg.=&Apache::bridgetask::add_request_another_attempt_button("Sign up for time to work");
 1380:         } elsif ($status eq 'RESERVABLE') {
 1381:             $msg.=&mt('Available to make a reservation.').' '.&mt('Reservation window closes [_1].',
 1382:                       &Apache::lonnavmaps::timeToHumanString($accessmsg,'end')).
 1383:                       '<br />'.
 1384:                       &Apache::bridgetask::add_request_another_attempt_button("Sign up for time to work");
 1385:         } elsif ($status eq 'RESERVABLE_LATER') {
 1386:             $msg.=&mt('Window to make a reservation will open [_1].',
 1387:                       &Apache::lonnavmaps::timeToHumanString($accessmsg,'start'));
 1388:         } elsif ($status eq 'NOTRESERVABLE') {
 1389:             $msg.=&mt('Not available to make a reservation.');
 1390:         } elsif ($status eq 'NEED_DIFFERENT_IP') {
 1391:             if ($ipused) {
 1392:                 $msg.=&mt('You must use the same computer ([_1]) you used when you first accessed this resource using your time/place-based reservation.',"IP: $ipused");
 1393:             } else {
 1394:                 $msg.=&mt('Each student must use a different computer to access this resource at this time and/or place.').'<br />'.
 1395:                       &mt('Somebody else has already used this particular computer for that purpose.');
 1396:             }
 1397:         }
 1398:         $msg.='<br />';
 1399:     } elsif ($target eq 'tex') {
 1400:         my $startminipage = ($env{'form.problem_split'}=~/yes/i)? ''
 1401:                              : '\begin{minipage}{\textwidth}';
 1402: 
 1403:         $msg ='\noindent \vskip 1 mm '.
 1404:               $startminipage.'\vskip 0 mm';
 1405:         if ($status eq 'UNAVAILABLE') {
 1406:             $msg.=&mt('Unable to determine if this resource is open due to network problems. Please try again later.').'\vskip 0 mm ';
 1407:         } else {
 1408:             $msg.=&mt('Problem is not open to be viewed. It')." $accessmsg \\vskip 0 mm ";
 1409:         }
 1410:     }
 1411:     return $msg;
 1412: }
 1413: 
 1414: sub checkin_prompt {
 1415:     my ($target,$slot_name,$slot,$type) = @_;
 1416:     my $result; 
 1417:     if ($target eq 'web') {
 1418:         $result = &Apache::bridgetask::proctor_validation_screen($slot);
 1419:     } elsif ($target eq 'grade') {
 1420:         if (!&Apache::bridgetask::proctor_check_auth($slot_name,$slot,$type)) {
 1421:             $result = &mt('An error occurred during check-in');
 1422:         }
 1423:     }
 1424:     return $result;
 1425: }
 1426: 
 1427: sub selfcheckin_resource {
 1428:     my ($resource_due,$slot_name,$slot,$symb) = @_;
 1429:     if ($slot_name ne '') {
 1430:         my $checked_in =
 1431:             $Apache::lonhomework::history{'resource.0.checkedin'};
 1432:         if ($checked_in eq '') {
 1433:             # unproctored slot access, self checkin
 1434:             my $needsiptied;
 1435:             if (ref($slot)) {
 1436:                 $needsiptied = $slot->{'iptied'};
 1437:             }
 1438:             my $check = &Apache::bridgetask::check_in('problem',undef,undef,
 1439:                                                       $slot_name,$needsiptied);
 1440:             if ($check =~ /^error: /) {
 1441:                 &Apache::lonnet::logthis("Error during self-checkin of problem (symb: $symb) using slot: $slot_name");
 1442:             } else {
 1443:                 $checked_in = $Apache::lonhomework::results{"resource.0.checkedin"};
 1444:             }
 1445:         }
 1446:         if ((ref($slot) eq 'HASH') && ($checked_in ne '')) {
 1447:             if ($slot->{'starttime'} < time()) {
 1448:                 if (!$resource_due) {
 1449:                     $resource_due = $slot->{'endtime'};
 1450:                 } elsif ($slot->{'endtime'} < $resource_due) {
 1451:                     $resource_due = $slot->{'endtime'};
 1452:                 }
 1453:             }
 1454:         }
 1455:     }
 1456:     return $resource_due;
 1457: }
 1458: 
 1459: sub checkout_msg {
 1460:     my %lt=&Apache::lonlocal::texthash( 
 1461: 		'resource'=>'The resource needs to be checked out',
 1462: 		'id_expln'=>'As a resource gets checked out, a unique timestamped ID is given to it, and a permanent record is left in the system.',
 1463:                 'warning'=>'Checking out resources is subject to course policies, and may exclude future credit even if done erroneously.',
 1464:                 'checkout'=>'Check out Bubblesheet Exam for Viewing',
 1465: 		'checkout?'=>'Check out Bubblesheet Exam?');
 1466:     my $uri = &Apache::lonenc::check_encrypt($env{'request.uri'});
 1467:     return (<<ENDCHECKOUT);
 1468: <h2>$lt{'resource'}</h2>
 1469:     <p>$lt{'id_expln'}</p>
 1470: <p class="LC_warning">$lt{'warning'}</p>
 1471: <form name="checkout" method="post" action="$uri">
 1472: <input type="hidden" name="doescheckout" value="yes" />
 1473: <input type="button" name="checkoutbutton" value="$lt{'checkout'}" onclick="javascript:if (confirm('$lt{'checkout?'}')) { document.checkout.submit(); }" />
 1474: </form>
 1475: ENDCHECKOUT
 1476: }
 1477: 
 1478: sub firstaccess_msg {
 1479:     my ($time,$symb)=@_;
 1480:     my $result;
 1481:     my @interval=&Apache::lonnet::EXT("resource.0.interval");
 1482:     if ($interval[1] eq 'map') {
 1483: 	my ($map)=&Apache::lonnet::decode_symb($symb);
 1484: 	my $foldertitle=&Apache::lonnet::gettitle($map);
 1485:     
 1486: 	&Apache::lonxml::debug("map is $map title is $foldertitle");
 1487: 	$result .= "<h2>".&mt('The resources in "[_1]" are open for a limited time.',$foldertitle)."</h2>"
 1488:                              .'<p>'.&mt('Once you click the "Show Resource" button below you have [_2] to complete all resources "[_1]".'
 1489:                              ,$foldertitle,$time)."</p>";
 1490:     } elsif ($interval[1] eq 'course') {
 1491: 	my $course = $env{'course.'.$env{'request.course.id'}.'.description'};
 1492:         $result .= "<h2>".&mt('The resources in "[_1]" are open for a limited time.',$course)."</h2>"
 1493:                              .'<p>'.&mt('Once you click the "Show Resource" button below you have [_2] to complete all resources "[_1]".'
 1494:                              ,$course,$time)."</p>";
 1495:     } else {
 1496: 	my $title=&Apache::lonnet::gettitle($symb);
 1497:         $result .= "<h2>".&mt('This resource "[_1]" is open for a limited time.',$title)."</h2>"
 1498:                              .'<p>'.&mt('Once you click the "Show Resource" button below you have [_2] to complete this resource "[_1]".'
 1499:                              ,$title,$time)."</p>";
 1500:     }
 1501:     my $uri = &Apache::lonenc::check_encrypt($env{'request.uri'});
 1502:     my $buttontext = &mt('Show Resource');
 1503:     my $timertext = &mt('Start Timer?');
 1504:     $result .= (<<ENDCHECKOUT);
 1505: <form name="markaccess" method="post" action="$uri">
 1506: <input type="hidden" name="markaccess" value="yes" />
 1507: <input type="button" name="accessbutton" value="$buttontext" onclick="javascript:if (confirm('$timertext')) { document.markaccess.submit(); }" />
 1508: </form>
 1509: ENDCHECKOUT
 1510:     return $result;
 1511: }
 1512: 
 1513: sub init_problem_globals {
 1514:     my ($type)=@_;
 1515:     #initialize globals
 1516:     #   For problems, we start out in part 0 (outside a <part> tag).
 1517:     #   and part 0 is used to describe the main body of the <problem>
 1518:     #
 1519:     if ($type eq 'problem') {
 1520: 	$Apache::inputtags::part='0';
 1521: 	@Apache::inputtags::partlist=('0');
 1522: 	&Apache::lonhomework::set_show_problem_status(&get_problem_status('0'));
 1523: 	$Apache::lonhomework::ignore_response_errors=0;
 1524: 
 1525:     } elsif ($type eq 'library') {
 1526: 	$Apache::inputtags::part='';
 1527: 	@Apache::inputtags::partlist=();
 1528: 	&Apache::lonhomework::reset_show_problem_status();
 1529: 	$Apache::lonhomework::ignore_response_errors=1;
 1530: 
 1531:     } elsif ($type eq 'Task') {
 1532: 	$Apache::inputtags::part='0';
 1533: 	@Apache::inputtags::partlist=('0');
 1534: 	&Apache::lonhomework::reset_show_problem_status();
 1535: 	$Apache::lonhomework::ignore_response_errors=1;
 1536:     }
 1537:     @Apache::functionplotresponse::callscripts=();
 1538:     @Apache::inputtags::responselist = ();
 1539:     @Apache::inputtags::importlist = ();
 1540:     @Apache::inputtags::previous=();
 1541:     @Apache::inputtags::previous_version=();
 1542:     $Apache::inputtags::leniency='';
 1543:     $Apache::structuretags::printanswer='No';
 1544:     @Apache::structuretags::whileconds=();
 1545:     @Apache::structuretags::whilebody=();
 1546:     @Apache::structuretags::whileline=();
 1547:     $Apache::lonhomework::scantronmode=0;
 1548:     undef($Apache::lonhomework::name);
 1549:     undef($Apache::lonhomework::default_type);
 1550:     undef($Apache::lonhomework::type);
 1551: }
 1552: 
 1553: sub reset_problem_globals {
 1554:     my ($type)=@_;
 1555:     undef(%Apache::lonhomework::history);
 1556:     undef(%Apache::lonhomework::results);
 1557:     undef($Apache::inputtags::part);
 1558:     undef($Apache::inputtags::leniency);
 1559:     if ($type eq 'Task') {
 1560:         undef($Apache::inputtags::slot_name);
 1561:     } elsif ($type eq 'problem') {
 1562:         undef($Apache::lonhomework::rawrndseed);
 1563:     }
 1564: #don't undef this, lonhomework.pm takes care of this, we use this to 
 1565: #detect if we try to do 2 problems in one file
 1566: #   undef($Apache::lonhomework::parsing_a_problem);
 1567:     undef($Apache::lonhomework::name);
 1568:     undef($Apache::lonhomework::default_type);
 1569:     undef($Apache::lonhomework::type);
 1570:     undef($Apache::lonhomework::scantronmode);
 1571:     undef($Apache::lonhomework::ignore_response_errors);
 1572:     undef(@Apache::functionplotresponse::callscripts);
 1573:     &Apache::lonhomework::reset_show_problem_status();
 1574: }
 1575: 
 1576: sub set_problem_state {
 1577:     my ($part)=@_;
 1578:     if ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct') {
 1579: 	$Apache::lonhomework::history{"resource.$part.solved"}=
 1580: 	    'correct_by_student';
 1581:     }
 1582: }
 1583: 
 1584: sub get_problem_status {
 1585:     my ($part)=@_;
 1586:     my $problem_status;
 1587:     if ($env{'request.state'} eq 'construct' &&
 1588: 	defined($env{'form.problemstatus'})) {
 1589: 	$problem_status=$env{'form.problemstatus'};
 1590:     } else {
 1591: 	$problem_status=&Apache::lonnet::EXT("resource.$part.problemstatus");
 1592: 	&Apache::lonxml::debug("problem status for $part is $problem_status");
 1593: 	&Apache::lonxml::debug("env probstat is ".$env{'form.problemstatus'});
 1594:     }
 1595:     return $problem_status;
 1596: }
 1597: 
 1598: sub start_problem {
 1599:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1600: 
 1601:     # We'll use the redirection to fix up printing of duedates.
 1602:     if (!$Apache::lonxml::metamode) {
 1603: 	&Apache::lonxml::startredirection();
 1604:     }
 1605: 
 1606:     # Problems don't nest and we don't allow more than one <problem> in
 1607:     # a .problem file.
 1608:     #
 1609:     if ( $Apache::inputtags::part ne '' ||
 1610: 	 $Apache::lonhomework::parsing_a_problem) {
 1611: 	&Apache::lonxml::error('Only one &lt;problem&gt; allowed in a .problem file');
 1612: 	#my $bodytext=&Apache::lonxml::get_all_text("/problem",$parser,$style);
 1613: 	return '';
 1614:     }
 1615: 
 1616:     $Apache::lonhomework::parsing_a_problem=1;
 1617:     &init_problem_globals('problem');
 1618: 
 1619:     if (defined($env{'scantron.maxquest'})) {
 1620: 	$Apache::lonhomework::scantronmode=1;
 1621:     }
 1622: 
 1623:     if ($target ne 'analyze') {
 1624:         my $type = &Apache::lonnet::EXT('resource.0.type');
 1625: 	$Apache::lonhomework::type=$type;
 1626: 	if (($env{'request.state'} eq 'construct') &&
 1627: 	    $env{'form.problemtype'} =~ /\S/) {
 1628: 	    $Apache::lonhomework::type=$env{'form.problemtype'};
 1629: 	}
 1630: 	&Apache::lonxml::debug("Found this to be of type :$Apache::lonhomework::type:");
 1631:     }
 1632:     if ($Apache::lonhomework::type eq '' ) {
 1633: 	my $uri=$env{'request.uri'};
 1634: 	if ($uri=~/\.(\w+)$/) {
 1635: 	    $Apache::lonhomework::type=$1;
 1636: 	    &Apache::lonxml::debug("Using type of $1");
 1637: 	} else {
 1638: 	    $Apache::lonhomework::type='problem';
 1639: 	    &Apache::lonxml::debug("Using default type, problem, :$uri:");
 1640: 	}
 1641:     }
 1642:     $Apache::lonhomework::default_type = $Apache::lonhomework::type;
 1643: 
 1644:     &initialize_storage();
 1645:     if ($target ne 'analyze'
 1646:        	&& $env{'request.state'} eq 'construct') {
 1647: 	&set_problem_state('0');
 1648:     }
 1649: 
 1650:     if ($target eq 'web') {
 1651: 	&Apache::lonxml::debug(" grading history ");
 1652: 	&Apache::lonhomework::showhash(%Apache::lonhomework::history);
 1653:     }
 1654: 
 1655:     #added vars to the scripting enviroment
 1656:     my $expression='$external::part=\''.$Apache::inputtags::part.'\';';
 1657:     $expression.='$external::type=\''.$Apache::lonhomework::type.'\';';
 1658:     &Apache::run::run($expression,$safeeval);
 1659:     my $status;
 1660:     my $accessmsg;
 1661:     my $resource_due;
 1662:     my $ipused;
 1663: 
 1664:     my $name= &get_resource_name($parstack,$safeeval);
 1665:     my ($result,$form_tag_start,$slot_name,$slot,$probpartlist);
 1666: 
 1667:     if ($target eq 'web' || $target eq 'grade' || $target eq 'answer' ||
 1668:         $target eq 'tex') {
 1669:         if ($env{'form.markaccess'}) {
 1670:             my @interval=&Apache::lonnet::EXT("resource.0.interval");
 1671:             my ($timelimit) = split(/_/,$interval[0]);
 1672:             &Apache::lonnet::set_first_access($interval[1],$timelimit);
 1673:         }
 1674:     }
 1675: 
 1676:     if ($target eq 'web' || $target eq 'webgrade' || $target eq 'tex'
 1677: 	|| $target eq 'edit') {
 1678: 	($result,$form_tag_start,$probpartlist) =
 1679: 	    &page_start($target,$token,$tagstack,$parstack,$parser,$safeeval,
 1680: 			$name);
 1681:     } elsif ((($target eq 'grade') && ($Apache::lonhomework::type eq 'randomizetry')) ||
 1682:              ($target eq 'answer')) {
 1683:         my ($symb)= &Apache::lonnet::whichuser();
 1684:         my $navmap = Apache::lonnavmaps::navmap->new();
 1685:         if (ref($navmap)) {
 1686:             my $res = $navmap->getBySymb($symb);
 1687:             if (ref($res)) {
 1688:                 $probpartlist = $res->parts();
 1689:             }
 1690:         }
 1691:     }
 1692: 
 1693:     if ($target eq 'web' || $target eq 'grade' || $target eq 'answer' ||
 1694:         $target eq 'tex') {
 1695: 
 1696:         my ($symb)= &Apache::lonnet::whichuser();
 1697:         ($status,$accessmsg,$slot_name,$slot,$ipused) =
 1698:             &Apache::lonhomework::check_slot_access('0','problem',$symb,$probpartlist);
 1699:         push (@Apache::inputtags::status,$status);
 1700:     }
 1701: 
 1702:     if ($target eq 'tex' and $env{'request.symb'} =~ m/\.page_/) {$result='';}
 1703: 
 1704:     if ($target eq 'analyze') { my $rndseed=&setup_rndseed($safeeval,$target); }
 1705:     if ($target eq 'web' || $target eq 'grade' || $target eq 'answer' ||
 1706: 	$target eq 'tex') {
 1707: 
 1708: 	#handle rand seed in construction space
 1709: 	my $rndseed=&setup_rndseed($safeeval,$target,$probpartlist);
 1710:         if (($target eq 'grade') && &Apache::response::submitted()) {
 1711:             if ($Apache::lonhomework::type eq 'randomizetry') {
 1712:                 $Apache::lonhomework::results{'resource.0.rndseed'}=$rndseed;
 1713:             } else {
 1714:                 my @parts;
 1715:                 if (ref($probpartlist) eq 'ARRAY') {
 1716:                     @parts = @{$probpartlist};
 1717:                 }
 1718:                 unless (@parts) {
 1719:                     $Apache::lonhomework::results{'resource.0.rndseed'}=$Apache::lonhomework::rawrndseed;
 1720:                 }
 1721:             }
 1722:         }
 1723: 	my ($symb)=&Apache::lonnet::whichuser();
 1724: 
 1725: 	if ($env{'request.state'} ne "construct" && 
 1726: 	    ($symb eq '' || $Apache::lonhomework::type eq 'practice')) {
 1727: 	    $form_tag_start.='<input type="hidden" name="rndseed" value="'.
 1728: 		$rndseed.'" />'.
 1729: 		    '<button type="submit" name="resetdata"
 1730:                         value="new_problem_variation">'.&mt('New Problem Variation').'</button>';
 1731: 	    if (exists($env{'form.username'})) {
 1732: 		$form_tag_start.=
 1733: 		    '<input type="hidden" name="username"
 1734:                              value="'.$env{'form.username'}.'" />';
 1735: 	    }
 1736: 	    if ($env{'request.role.adv'}) {
 1737: 		$form_tag_start.= ' <label class="LC_nobreak">'
 1738:                          .'<input type="checkbox" name="showallfoils"';
 1739: 		if (defined($env{'form.showallfoils'})) {
 1740: 		    $form_tag_start.=' checked="checked"';
 1741: 		}
 1742:                 $form_tag_start.= ' /> '
 1743:                                  .&mt('Show All Foils')
 1744:                                  .'</label>';
 1745: 	    }
 1746:             if ($Apache::lonhomework::type eq 'practice') {
 1747:                 $form_tag_start.=&practice_problem_header();
 1748:             }
 1749: 	    $form_tag_start.='<hr />';
 1750:         } elsif (($env{'request.state'} ne "construct") &&
 1751:                  ($Apache::lonhomework::type eq 'randomizetry') &&
 1752:                  ($status eq 'CAN_ANSWER') &&
 1753:                  ($env{'course.'.$env{'request.course.id'}.'.type'} ne 'Placement') &&
 1754:                  (!$env{'request.role.adv'})) {
 1755: # "New Problem Variation Each Try" header suppressed for Placement Tests, unless course personnel. 
 1756:             my $reqtries = &Apache::lonnet::EXT("resource.$Apache::inputtags::part.randomizeontries");
 1757:             my $problemstatus = &get_problem_status($Apache::inputtags::part);
 1758:             $form_tag_start.=&randomizetry_problem_header($problemstatus,$reqtries);
 1759:         }
 1760: 
 1761: 	my $expression='$external::datestatus="'.$status.'";';
 1762: 	$expression.='$external::gradestatus="'.$Apache::lonhomework::history{"resource.0.solved"}.'";';
 1763: 	&Apache::run::run($expression,$safeeval);
 1764: 	&Apache::lonxml::debug("Got $status");
 1765: 
 1766: 	if (( $status eq 'CLOSED' ) ||
 1767: 	    ( $status eq 'UNCHECKEDOUT') ||
 1768: 	    ( $status eq 'NOT_YET_VIEWED') ||
 1769: 	    ( $status eq 'BANNED') ||
 1770: 	    ( $status eq 'UNAVAILABLE') ||
 1771: 	    ( $status eq 'NOT_IN_A_SLOT') ||
 1772:             ( $status eq 'NOTRESERVABLE') ||
 1773:             ( $status eq 'RESERVABLE') ||
 1774:             ( $status eq 'RESERVABLE_LATER') ||
 1775: 	    ( $status eq 'INVALID_ACCESS') ||
 1776:             ( $status eq 'NEED_DIFFERENT_IP')) {
 1777: 	    my $bodytext=&Apache::lonxml::get_all_text("/problem",$parser,
 1778: 						       $style);
 1779:             $result .= &access_status_msg('problem',$status,$symb,$target,$ipused,$accessmsg);
 1780: 	} elsif ($status eq 'NEEDS_CHECKIN') {
 1781: 	    my $bodytext=&Apache::lonxml::get_all_text("/problem",$parser,
 1782: 						       $style);
 1783:             $result .= &checkin_prompt($target,$slot_name,$slot,'problem');
 1784: 	} elsif ($target eq 'web') {
 1785: 	    if ($status eq 'CAN_ANSWER') {
 1786:                 $resource_due = &Apache::lonhomework::due_date(0, $env{'request.symb'});
 1787:                 if ($slot_name ne '') {
 1788:                     $resource_due = &selfcheckin_resource($resource_due,$slot_name,$slot,
 1789:                                                           $env{'request.symb'});
 1790:                 }
 1791:                 if ($resource_due) {
 1792:                     my $time_left = $resource_due - time();
 1793:                     if ($resource_due && ($time_left > 0) && ($target eq 'web')) {
 1794:                         $result .= &Apache::lonhtmlcommon::set_due_date($resource_due);
 1795:                     }
 1796:                 }
 1797:             }
 1798: 	    $result.="\n $form_tag_start \t".	
 1799: 	      '<input type="hidden" name="submitted" value="yes" />';
 1800: 	    # create a page header and exit
 1801: 	    if ($env{'request.state'} eq "construct") {
 1802:                 if ($env{'form.inhibitmenu'} eq 'yes') {
 1803:                     # error messages can be useful in any case
 1804:                     $result.= &Apache::lonxml::message_location();
 1805:                 } else {
 1806: 		    $result.= &problem_web_to_edit_header($env{'form.rndseed'});
 1807:                 }
 1808:                 if ($Apache::lonhomework::type eq 'practice') {
 1809:                     $result.= '<button type="submit" name="resetdata" '.
 1810:                         'value="new_problem_variation">'.&mt('New Problem Variation').'</button>'.
 1811:                         &practice_problem_header().'<hr />';
 1812:                 }
 1813: 	    }
 1814: 	    # if we are viewing someone else preserve that info
 1815: 	    if (defined $env{'form.grade_symb'}) {
 1816: 		foreach my $field ('symb','courseid','domain','username') {
 1817: 		    $result .= '<input type="hidden" name="grade_'.$field.
 1818: 			'" value="'.$env{"form.grade_$field"}.'" />'."\n";
 1819: 		}
 1820:                 foreach my $field ('trial','questiontype') {
 1821:                     if ($env{"form.grade_$field"} ne '') {
 1822:                         $result .= '<input type="hidden" name="grade_'.$field.
 1823:                             '" value="'.$env{"form.grade_$field"}.'" />'."\n";
 1824:                     }
 1825:                 }
 1826: 	    }
 1827:             if ($env{'form.grade_imsexport'}) {
 1828:                 $result = '';
 1829:             }
 1830: 	} elsif ($target eq 'tex') {
 1831: 	    $result .= 'INSERTTEXFRONTMATTERHERE';
 1832: 	    $result .= &select_metadata_hyphenation();
 1833: 	}
 1834:     } elsif ($target eq 'edit') {
 1835: 	$result .= $form_tag_start.&problem_edit_header();
 1836: 	$Apache::lonxml::warnings_error_header=
 1837: 	    &mt("Editor Errors - these errors might not effect the running of the problem, but they will likely cause problems with further use of the Edit mode. Please use the EditXML mode to fix these errors.")."<br />";
 1838: 	my $temp=&Apache::edit::insertlist($target,$token);
 1839: 	$result.=$temp;
 1840:     } elsif ($target eq 'modified') {
 1841: 	$result=$token->[4];
 1842:     } else {
 1843: 	# page_start returned a starting result, delete it if we don't need it
 1844: 	$result = '';
 1845:     }
 1846:     return $result;
 1847: }
 1848: 
 1849: sub end_problem {
 1850:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 1851:     my $result;
 1852: 
 1853:     if (!$Apache::lonxml::metamode) {
 1854: 	$result = &Apache::lonxml::endredirection(); #started in &start_problem
 1855: 	$Apache::lonxml::post_evaluate=0;
 1856:     }
 1857: 
 1858:     if ($target eq 'tex') {
 1859: 	# Figure out the front matter and replace the
 1860: 	# INSERTTEXFRONTMATTERHERE in result with it.  note that we do
 1861: 	# this in end_problem because whether or not we display due
 1862: 	# dates depends on whether due dates have already been
 1863: 	# displayed in the problem parts.
 1864: 
 1865: 	my $frontmatter   = '';
 1866: 	my $startminipage = '';
 1867: 	if (not $env{'form.problem_split'}=~/yes/) {
 1868: 	    $startminipage = '\begin{minipage}{\textwidth}';
 1869: 	}
 1870: 	my $id = $Apache::inputtags::part;
 1871: 	my $weight = &Apache::lonnet::EXT("resource.$id.weight");
 1872: 	my $packages=&Apache::lonnet::metadata($env{'request.uri'},'packages');
 1873: 	my @packages = split(/,/,$packages);
 1874: 	my $allow_print_points = 0;
 1875: 	foreach my $partial_key (@packages) {
 1876: 	    if ($partial_key=~m/^part_0$/) {
 1877: 		$allow_print_points=1;
 1878: 	    }
 1879: 	}
 1880: 	my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
 1881: 	if (defined($maxtries) && $maxtries < 0) { $allow_print_points=0; }
 1882: 	if (lc($env{'course.'.$env{'request.course.id'}.
 1883: 			'.disableexampointprint'}) eq 'yes') {
 1884: 	    $allow_print_points=0;
 1885: 	}
 1886: 	my $name_of_resourse= &Apache::lonxml::latex_special_symbols(&get_resource_name($parstack,$safeeval),'header');
 1887: 	my $begin_doc=' \typeout{STAMPOFPASSEDRESOURCESTART Resource <h2>"'.$name_of_resourse.'"</h2> located in <br /><small><b>'.$env{'request.uri'}.'</b></small><br /> STAMPOFPASSEDRESOURCEEND} \noindent ';
 1888: 	&clear_required_languages();
 1889: 	my $toc_line='\vskip 1 mm\noindent '.$startminipage.
 1890: 	    '\addcontentsline{toc}{subsection}{'.$name_of_resourse.'}';
 1891: 	
 1892: 	#  Figure out what the due date is and if we need to print
 1893: 	#  it in the problem header.  We have been logging the
 1894: 	#  last due date written to file. 
 1895: 	
 1896: 	my $duetime = &Apache::lonnet::EXT("resource.$id.duedate"); 
 1897: 	my $duedate = POSIX::strftime("%c",localtime($duetime));
 1898:         my $duedate_text = &mt('Due date: [_1]'
 1899:                               ,&Apache::lonlocal::locallocaltime($duetime));
 1900: 	my $temp_file;
 1901: 	my $filename = "/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout.due";
 1902: 	
 1903: 	# Figure out what the last printed due date is or set it
 1904: 	# to the epoch if no duedates have been printed.
 1905: 	
 1906: 	my $due_file_content = 0;      #   If the file does not yet exist, time is the epoch.
 1907: 	if (-e $filename) {
 1908: 	    $temp_file = Apache::File->new($filename);
 1909: 	    my @due_file      = <$temp_file>;
 1910: 	    $due_file_content = $due_file[$#due_file];
 1911: 	    chomp $due_file_content;
 1912: 	} 
 1913: 	
 1914: 	# We display the due date iff it is not the same as the last
 1915: 	# duedate in problem header ($due_file_content), and
 1916: 	# none of our parts displayed a duedate.
 1917: 	#
 1918: 	my $parts_with_displayduedate;
 1919: 	if (defined $Apache::outputtags::showonce{'displayduedate'}) {
 1920: 	    $parts_with_displayduedate = 
 1921: 		scalar(@{$Apache::outputtags::showonce{'displayduedate'}});
 1922: 	} else {
 1923: 	    $parts_with_displayduedate = 0;
 1924: 	}
 1925: 	if (($due_file_content != $duetime) && ($parts_with_displayduedate == 0) ) {
 1926: 	    $temp_file = Apache::File->new('>'.$filename);
 1927: 	    print $temp_file "$duetime\n";
 1928: 	    if (not $env{'request.symb'} =~ m/\.page_/) {
 1929: 		if(not $duedate=~m/1969/ and $Apache::lonhomework::type ne 'exam') {
 1930: 		    $frontmatter .= $begin_doc.
 1931: 			'\textit{'.$duedate_text.'} '.$toc_line;
 1932: 		} else {
 1933: 		    $frontmatter.= $begin_doc.$toc_line;
 1934: 		    if ($Apache::lonhomework::type eq 'exam' and $allow_print_points==1) { 
 1935: 			$frontmatter .= '\fbox{\textit{'.&mt('[quant,_1,pt,pt]',$weight ).'}}';
 1936: 		    }
 1937: 		}
 1938: 	    } else {
 1939: 		$frontmatter .= '\vskip 1mm\textit{'.$duedate_text.'} \\\\\\\\'.$startminipage;
 1940: 	    }
 1941: 	} else {
 1942: 	    if (not $env{'request.symb'} =~ m/\.page_/) {
 1943: 		$frontmatter .= $begin_doc.$toc_line;
 1944: 		if (($Apache::lonhomework::type eq 'exam') and ($allow_print_points==1)) { 
 1945: 		    $frontmatter .= '\fbox{\textit{'.&mt('[quant,_1,pt,pt]',$weight ).'}}';
 1946: 		}
 1947: 	    } else {
 1948: 		$frontmatter .= '\vskip 1mm \\\\\\\\'.$startminipage;
 1949: 	    }
 1950: 	}
 1951: 	$result =~ s/INSERTTEXFRONTMATTERHERE/$frontmatter/;
 1952:     }
 1953: 
 1954:     my $status=$Apache::inputtags::status['-1'];
 1955:     if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' ||
 1956: 	$target eq 'tex') {
 1957: 	if ( $target eq 'grade' && $Apache::inputtags::part eq '0') {
 1958: 	    # if part is zero, no <part>s existed, so we need to the grading
 1959: 	    if ($status eq 'CAN_ANSWER' ||$Apache::lonhomework::scantronmode) {
 1960: 		&Apache::inputtags::grade;
 1961: 	    } elsif ($status eq 'NEEDS_CHECKIN') {
 1962: 		# no need to grade, and don't want to hide data
 1963: 	    } else {
 1964: 		# move any submission data to .hidden
 1965: 		&Apache::inputtags::hidealldata($Apache::inputtags::part);
 1966: 	    }
 1967: 	} elsif ( ($target eq 'web' || $target eq 'tex') &&
 1968: 		  $Apache::inputtags::part eq '0' &&
 1969: 		  $status ne 'UNCHECKEDOUT' && $status ne 'NOT_YET_VIEWED'
 1970:                   && !$env{'form.grade_imsexport'}) {
 1971: 	    # if part is zero, no <part>s existed, so we need show the current
 1972: 	    # grading status
 1973: 	    my $gradestatus = &Apache::inputtags::gradestatus($Apache::inputtags::part,$target);
 1974: 	    $result.= $gradestatus;
 1975: 	}
 1976: 	if (
 1977: 	    (($target eq 'web') && ($env{'request.state'} ne 'construct')) ||
 1978: 	    ($target eq 'answer') || ($target eq 'tex')
 1979: 	   ) {
 1980: 	    if (($target ne 'tex') &&
 1981: 		($env{'form.answer_output_mode'} ne 'tex') && 
 1982:                 (!$env{'form.grade_imsexport'})) {
 1983: 		$result.="</form>";
 1984: 	    }
 1985: 	    if ($target eq 'web') {
 1986:                 #
 1987:                 # Closing </body></html> not added by end_page().
 1988:                 # Added separately at end of this routine, after added
 1989:                 # <script></script> so document will be valid xhtml.
 1990:                 #
 1991:                 my $showdisc = 1;
 1992:                 if (($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement') &&
 1993:                     (!$env{'request.role.adv'})) { 
 1994: # For Placement Tests footer with "Post Discussion" and "Send Feedback" links is suppressed.
 1995:                     $showdisc = 0;
 1996:                     my ($symb)= &Apache::lonnet::whichuser();
 1997:                     if ($symb) {
 1998:                         my $navmap = Apache::lonnavmaps::navmap->new();
 1999:                         if (ref($navmap)) {
 2000:                             my $hastries = &Apache::lonplacementtest::has_tries($symb,$navmap);  
 2001: # For Placement Tests test status is displayed if this is the last resource in the course
 2002: # and there are no tries left
 2003:                             unless ($hastries) {
 2004:                                 if (&Apache::lonplacementtest::is_lastres($symb,$navmap)) {
 2005:                                     my ($score,$incomplete) = 
 2006:                                         &Apache::lonplacementtest::check_completion(undef,undef,1);
 2007:                                     if (!$incomplete) {
 2008:                                         $result .= &Apache::lonplacementtest::showresult(1,1);
 2009:                                     } elsif ($incomplete < 100) { 
 2010:                                         $result.= &Apache::lonplacementtest::showincomplete($incomplete,1);
 2011:                                     }
 2012:                                 } else {
 2013: # For Placement Tests score is displayed if test has just been completed
 2014:                                     my ($score,$incomplete) = &Apache::lonplacementtest::check_completion(undef,undef,1);
 2015:                                     if (!$incomplete) {
 2016:                                         $result.= &Apache::lonplacementtest::showresult(1,1);
 2017:                                     }
 2018:                                 }
 2019:                             }
 2020:                         }
 2021:                     }
 2022:                 }
 2023: 		$result.= &Apache::loncommon::end_page({'discussion' => $showdisc,
 2024: 							'notbody'    => 1});
 2025: 	    } elsif ($target eq 'tex') {
 2026: 		my $endminipage = '';
 2027: 		if (not $env{'form.problem_split'}=~/yes/) {
 2028: 		    $endminipage = '\end{minipage}';
 2029: 		}
 2030:                 if ($env{'form.print_discussions'} eq 'yes') {
 2031: 		    $result.=&Apache::lonxml::xmlend($target,$parser);
 2032: 		} else {
 2033: 		    $result .= '\keephidden{ENDOFPROBLEM}\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}';
 2034: 		    if (not $env{'request.symb'} =~ m/\.page_/) {
 2035: 			$result .= $endminipage.'\end{document} ';
 2036: 		    } else {
 2037: 			$result .= $endminipage;
 2038: 		    }
 2039: 		}
 2040: 	    }
 2041: 	}
 2042:         if ($target eq 'web') {
 2043:            $result.=&Apache::functionplotresponse::init_script();
 2044:         }
 2045: 	if ($target eq 'grade') {
 2046: 	    &Apache::lonhomework::showhash(%Apache::lonhomework::results);
 2047: 	    &finalize_storage();
 2048: 	}
 2049: 	if ($target eq 'answer' && ($env{'request.state'} eq 'construct')
 2050: 	    && $env{'form.answer_output_mode'} ne 'tex') {
 2051: 	    $result.=&Apache::loncommon::end_page({'discussion' => 1});
 2052: 	                        # normally we get it from above, but in CSTR
 2053: 	                        # we always show answer mode too.
 2054: 	}
 2055:     } elsif ($target eq 'meta') {
 2056: 	if ($Apache::inputtags::part eq '0') {
 2057: 	    @Apache::inputtags::response=();
 2058: 	    $result=&Apache::response::mandatory_part_meta;
 2059: 	}
 2060: 	$result.=&Apache::response::meta_part_order();
 2061: 	$result.=&Apache::response::meta_response_order();
 2062:     } elsif ($target eq 'edit') {
 2063: 	&Apache::lonxml::debug("in end_problem with $target, edit");
 2064: 	$result .= &problem_edit_footer();
 2065:     } elsif ($target eq 'modified') {
 2066: 	 $result .= $token->[2];
 2067:     }
 2068: 
 2069:     if ($env{'request.state'} eq 'construct' && $target eq 'web') {
 2070: 	&Apache::inputtags::check_for_duplicate_ids();
 2071:     }
 2072: 
 2073:     &reset_problem_globals('problem');
 2074: 
 2075:     #
 2076:     # This shouild be just above the return so that the
 2077:     # time put in the javascript is as late as possible in the
 2078:     # computation:
 2079:     #
 2080:     if ($target eq 'web') {
 2081:         $result .= &Apache::lonhtmlcommon::set_compute_end_time();
 2082:         #
 2083:         # Closing tags delayed so any <script></script> tags 
 2084:         # not in head can appear inside body, for valid xhtml.
 2085:         # 
 2086:         $result .= "</body>\n</html>";
 2087:     }
 2088:     return $result;
 2089: }
 2090: 
 2091: 
 2092: sub start_library {
 2093:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2094:     my ($result,$form_tag_start);
 2095:     if ($#$tagstack eq 0 && $$tagstack[0] eq 'library') {
 2096: 	&init_problem_globals('library');
 2097: 	$Apache::lonhomework::type='problem';
 2098:     }
 2099:     if ($target eq 'edit') {
 2100: 	($result,$form_tag_start)=
 2101: 	    &page_start($target,$token,$tagstack,$parstack,$parser,$safeeval,
 2102: 			'Edit');
 2103: 	$result.=$form_tag_start.&problem_edit_header();
 2104: 	my $temp=&Apache::edit::insertlist($target,$token);
 2105: 	$result.=$temp;
 2106:     } elsif ($target eq 'modified') {
 2107: 	$result=$token->[4];
 2108:     } elsif (($target eq 'web' || $target eq 'webgrade')
 2109: 	     && ($#$tagstack eq 0 && $$tagstack[0] eq 'library')
 2110: 	     && $env{'request.state'} eq "construct" ) {
 2111: 	my $name=&get_resource_name($parstack,$safeeval);
 2112: 	($result,$form_tag_start)=
 2113: 	    &page_start($target,$token,$tagstack,$parstack,$parser,$safeeval,
 2114: 			$name);
 2115: 	my $rndseed=&setup_rndseed($safeeval,$target);
 2116: 	$result.=" \n $form_tag_start".	
 2117: 		  '<input type="hidden" name="submitted" value="yes" />';
 2118: 	$result.=&problem_web_to_edit_header($rndseed);
 2119:         if ($Apache::lonhomework::type eq 'practice') {
 2120:             $result.= '<button type="submit" name="resetdata" '.
 2121:                 'value="new_problem_variation">'.&mt('New Problem Variation').'</button>'.
 2122:                 &practice_problem_header().'<hr />';
 2123:         }
 2124:     }
 2125:     return $result;
 2126: }
 2127: 
 2128: sub end_library {
 2129:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2130:     my $result='';
 2131:     if ($target eq 'edit') {
 2132: 	$result=&problem_edit_footer();
 2133:     } elsif ($target eq 'web' 
 2134: 	     && ($#$tagstack eq 0 && $$tagstack[0] eq 'library') 
 2135: 	     && $env{'request.state'} eq "construct") {
 2136: 	$result.='</form>'.&Apache::loncommon::end_page({'discussion' => 1});
 2137:     }
 2138:     if ( $#$tagstack eq 0 && $$tagstack[0] eq 'library') {
 2139: 	&reset_problem_globals('library');
 2140:     }
 2141:     return $result;
 2142: }
 2143: 
 2144: sub start_definetag {
 2145:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2146: 
 2147:     my $result;
 2148: 
 2149:     my $name = $token->[2]->{'name'};
 2150:     my $skip=&Apache::lonxml::get_all_text("/definetag",$parser,$style);
 2151:     if ($target eq 'web') {
 2152: 	if ($name=~/^\//) {
 2153: 	    $result=
 2154: 		'<br /><table class="LC_sty_end"><tr><th>'.
 2155: 		&mt('END [_1]'.'<tt>'.$name.'</tt>').'</th></tr>';
 2156: 	} else {
 2157: 	    $result=
 2158: 		'<br /><table class="LC_sty_begin"><tr><th>'.
 2159: 		&mt('BEGIN [_1]'.'<tt>'.$name.'</tt>').'</th></tr>';
 2160: 	}
 2161: 	$skip = &HTML::Entities::encode($skip, '<>&"');
 2162: 	$result.='<tr><td><pre>'.$skip.'</pre></td></tr></table>';
 2163:     }
 2164:     return $result;
 2165: }
 2166: 
 2167: sub end_definetag {
 2168:     return '';
 2169: }
 2170: 
 2171: sub start_block {
 2172:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2173: 
 2174:     my $result;
 2175: 
 2176:     if ($target eq 'web' || $target eq 'grade'   || $target eq 'answer'  ||
 2177: 	$target eq 'tex' || $target eq 'analyze' || $target eq 'webgrade') {
 2178: 	my $code = $token->[2]->{'condition'};
 2179: 	if (defined($code) && $code ne '') {
 2180: 	    if (!$Apache::lonxml::default_homework_loaded) {
 2181: 		&Apache::lonxml::default_homework_load($safeeval);
 2182: 	    }
 2183: 	    $result = &Apache::run::run($code,$safeeval);
 2184: 	    &Apache::lonxml::debug("block :$code: returned :$result:");
 2185: 	} else {
 2186: 	    $result='1';
 2187: 	}
 2188: 	if ( ! $result ) {
 2189: 	    my $skip=&Apache::lonxml::get_all_text("/block",$parser,$style);
 2190: 	    &Apache::lonxml::debug("skipping ahead :$skip: $$parser[-1]");
 2191: 	}
 2192: 	$result='';
 2193:     } elsif ($target eq 'edit') {
 2194: 	$result .=&Apache::edit::tag_start($target,$token);
 2195: 	$result .=&Apache::edit::text_arg('Test Condition:','condition',
 2196: 					  $token,40);
 2197: 	$result .=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
 2198:     } elsif ($target eq 'modified') {
 2199: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
 2200: 						     $safeeval,'condition');
 2201: 	if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
 2202:     }
 2203:     return $result;
 2204: }
 2205: 
 2206: sub end_block {
 2207:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2208:     my $result;
 2209:     if ($target eq "edit") {
 2210: 	$result.= &Apache::edit::tag_end($target,$token,'');
 2211:     }
 2212:     return $result;
 2213: }
 2214: #
 2215: #  <languageblock [include='lang1,lang2...'] [exclude='lang1,lang2...']>
 2216: #  ...
 2217: #  </languageblock>
 2218: #
 2219: #   This declares the intent to provide content that can be rendered in the
 2220: #   set of languages in the include specificatino but not in the exclude
 2221: #   specification.  If a currently preferred language is in the include list
 2222: #   the content in the <languageblock>...</languageblock> is rendered
 2223: #   If the currently preferred language is in the exclude list,
 2224: #   the content in the <languageblock>..></languageblock is not rendered.
 2225: #
 2226: #   Pathalogical case handling:
 2227: #     - Include specified, without the preferred language but exclude  specified
 2228: #       also without the preferred langauge results in rendering the block.
 2229: #     - Exclude specified without include and excluden not containing a 
 2230: #       preferred language renders the block.
 2231: #     - Include and exclude both specifying the preferred language does not
 2232: #       render the block.
 2233: #     - If neither include/exclude is specified, the block gets rendered.
 2234: #
 2235: #  This tag has no effect when target is in {edit, modified}
 2236: #
 2237: sub start_languageblock {
 2238:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2239: 
 2240:     my $result = '';
 2241: 
 2242:     if ($target eq 'web' || $target eq 'grade'   || $target eq 'answer' ||
 2243: 	$target eq 'tex' || $target eq 'analyze' || $target eq 'webgrade') {
 2244: 	my $include = $token->[2]->{'include'};
 2245: 	my $exclude = $token->[2]->{'exclude'};
 2246:         my @preferred_languages=&Apache::lonlocal::preferred_languages();
 2247: 
 2248:         # This should not even happen, since we should at least have the server language
 2249: 
 2250:         if (!$preferred_languages[0]) { 
 2251: 	    $preferred_languages[0]='en'; 
 2252: 	}
 2253: 
 2254:         # Now loop over all languages in order of preference
 2255: 
 2256: 	my $render;
 2257:         foreach my $preferred_language (@preferred_languages) {
 2258: 
 2259: 	    # If neither include/nor exlude is present the block is going
 2260: 	    # to get rendered.
 2261: 
 2262:            my $found=0;
 2263:            $render=1;
 2264: 
 2265: 	   #  If include is specified,  don't render the block
 2266: 	   #  unless the preferred language is included in the set.
 2267: 
 2268: 	   if ($include) {
 2269:               $render=0;
 2270:               foreach my $included_language (split(/\,/,$include)) {
 2271:                  if ($included_language eq $preferred_language) {
 2272:                     $render=1; 
 2273:                     $found=1; 
 2274: 		    last;	# Only need to find the first.
 2275:                  }
 2276:               }
 2277: 	   }
 2278:            # Do we have an exclude argument?
 2279: 	   # If so, and one of the languages matches a preferred language
 2280: 	   # inhibit rendering the block.  Note that in the pathalogical case the
 2281: 	   # author has specified a preferred language in both the include and exclude
 2282: 	   # attribte exclude is preferred.  
 2283: 
 2284:            if ($exclude) {
 2285:               $render=1;
 2286:               foreach my $excluded_language (split(/\,/,$exclude)) {
 2287:                  if ($excluded_language eq $preferred_language) {
 2288:                     $render=0;
 2289:                     $found=1;
 2290: 		    last;	# Only need to find the first.
 2291:                  }
 2292:               }
 2293: 	   }
 2294:            if ($found) { 
 2295: 	       last; 		# Done on any match of include or exclude.
 2296: 	   }
 2297:         }
 2298: 	# If $render not true skip the entire block until </languageblock>
 2299: 	#
 2300: 
 2301: 	if ( ! $render ) {
 2302: 	    my $skip=&Apache::lonxml::get_all_text("/languageblock",$parser,
 2303: 						   $style);
 2304: 	    &Apache::lonxml::debug("skipping ahead :$skip: $$parser[-1]");
 2305: 	}
 2306: 	# If $render is true, we've not skipped the contents of the <languageglock>
 2307: 	# and the normal loncapa processing flow will render it as a matter of course.
 2308: 
 2309:     } elsif ($target eq 'edit') {
 2310: 	$result .=&Apache::edit::tag_start($target,$token);
 2311: 	$result .=&Apache::edit::text_arg(&mt('Include Language:'),'include',
 2312: 					  $token,40);
 2313: 	$result .=&Apache::edit::text_arg(&mt('Exclude Language:'),'exclude',
 2314: 					  $token,40);
 2315: 	$result .=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
 2316:     } elsif ($target eq 'modified') {
 2317: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
 2318: 						     $safeeval,'include',
 2319: 						     'exclude');
 2320: 	if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
 2321:     }
 2322:     return $result;
 2323: }
 2324: 
 2325: sub end_languageblock {
 2326:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2327:     my $result;
 2328:     if ($target eq "edit") {
 2329: 	$result.= &Apache::edit::tag_end($target,$token,'');
 2330:     }
 2331:     return $result;
 2332: }
 2333: #  languagblock specific tags:
 2334: {
 2335:     # For chunks of a resource that has translations, this hash contains
 2336:     # the translations available indexed by language name.
 2337:     #
 2338: 
 2339:     my %available_texts;       
 2340: 
 2341:     # <translated> starts a block of a resource that has multiple translations.
 2342:     # See the <lang> tag as well.
 2343:     # When </translated> is encountered if there is a translation for the 
 2344:     # currently preferred language, that is rendered inthe web/tex/webgrade
 2345:     # targets.  Otherwise, the default text is rendered.
 2346:     #
 2347:     # Note that <lang> is only registered for the duration of the 
 2348:     #  <translated>...</translated> block 
 2349:     #
 2350:     # Pathalogical case handling:
 2351:     #   - If there is no <lang> that specifies a 'default' and there is no
 2352:     #     translation that matches a preferred language, nothing is rendered.
 2353:     #   - Nested <translated>...</translated> might be linguistically supported by
 2354:     #     XML due to the stack nature of tag registration(?) however the rendered
 2355:     #     output will be incorrect because there is only one %available_texts
 2356:     #     has and end_translated clears it.
 2357:     #   - Material outside of a <lang>...</lang> block within the
 2358:     #     <translated>...<translated> block won't render either e.g.:
 2359:     #    <translated>
 2360:     #      The following will be in your preferred langauge:
 2361:     #      <lang which='en'>
 2362:     #         This section in english
 2363:     #      </lang>
 2364:     #      <lang which='sgeiso'>
 2365:     #         Hier es ist auf Deutsch.
 2366:     #      </lang>
 2367:     #      <lang which='sfriso'>
 2368:     #         En Francais
 2369:     #      </lang>
 2370:     #    </translated>
 2371:     #
 2372:     #    The introductory text prior to the first <lang> tag is not rendered.
 2373:     #
 2374:     sub start_translated {
 2375: 	my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2376: 	&Apache::lonxml::register('Apache::structuretags',('lang'));
 2377: 	undef(%available_texts);
 2378:     }
 2379:     
 2380:     sub end_translated {
 2381: 	my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2382: 	my $result;
 2383: 	#show the translation on viewable targets
 2384: 	if ($target eq 'web'     || $target eq 'tex' || $target eq 'webgrade'||
 2385: 	    # or non-viewable targets, if it's embedded in something that
 2386: 	    # wants the output
 2387: 	    (($target eq 'answer' || $target eq 'analyze'|| $target eq 'grade')
 2388: 	     && &Apache::lonxml::in_redirection() ) ) {
 2389: 	    my @possibilities = keys(%available_texts);
 2390: 	    my $which = 
 2391: 		&Apache::loncommon::languages(\@possibilities) || 'default';
 2392: 	    if ($target eq 'tex') {
 2393: 		$result = &select_hyphenation($which);
 2394: 	    }
 2395: 	    $result .= $available_texts{$which};
 2396: 	    if ($target eq 'tex') {
 2397: 		$result .= &select_metadata_hyphenation(); # Restore original language.
 2398: 	    }
 2399: 	}
 2400: 	undef(%available_texts);
 2401: 	&Apache::lonxml::deregister('Apache::structuretags',('lang'));
 2402: 	return $result;
 2403:     }
 2404: 
 2405:     # <lang [which='language-name'] [other='lang1,lang2...']>  
 2406:     #  Specifies that the block contained within it is a translation 
 2407:     #  for a specific language specified by the 'which' attribute. The
 2408:     #   'other' attribute can be used by itself or in conjunction with
 2409:     #   which to specify this tag _may_ be used as a translation for some
 2410:     #   list of languages. e.g.:  <lang which='senisoUS' other='senisoCA,senisoAU,seniso'>
 2411:     #   specifying that the block provides a translation for US (primary)
 2412:     #   Canadian, Australian and UK Englush.
 2413:     #   
 2414:     # Comment: this seems a bit silly why not just support a list of languages
 2415:     #           e.g. <lang which='l1,l2...'> and ditch the other attribute?
 2416:     #
 2417:     #  Effect:
 2418:     #    The material within the <lang>..</lang> block is stored in the
 2419:     #    specified set of $available_texts hash entries, the appropriate one
 2420:     #    is selected at </translated> time.
 2421:     #
 2422:     #  Pathalogical case handling:
 2423:     #    If a language occurs multiple times within a <translated> block,
 2424:     #    only the last one is rendered e.g.:
 2425:     #
 2426:     #    <translated>
 2427:     #       <lang which='senisoUS', other='senisoCA,senisoAU,seniso'>
 2428:     #          Red green color blindness is quite common affecting about 7.8% of 
 2429:     #          the male population, but onloy about .65% of the female population.
 2430:     #       </lang>
 2431:     #          Red green colour blindness is quite common affecting about 7.8% of 
 2432:     #          the male population, but onloy about .65% of the female population.
 2433:     #       <lang which='seniso', other='senisoCA,senisoAU'>
 2434:     #     </translated>
 2435:     #
 2436:     #    renders the correct spelling of color (colour) for people who have specified
 2437:     #    a preferred language that is one of the British Commonwealth languages
 2438:     #    even though those are also listed as valid selections for the US english
 2439:     #    <lang> block.
 2440:     #
 2441:     sub start_lang {
 2442: 	my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2443: 	if ($target eq 'web' || $target eq 'grade'   || $target eq 'answer' ||
 2444: 	    $target eq 'tex' || $target eq 'analyze' || $target eq 'webgrade') {
 2445: 	    &Apache::lonxml::startredirection();
 2446: 	}
 2447: 	return '';
 2448:     }
 2449: 
 2450:     sub end_lang {
 2451: 	my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2452: 	if ($target eq 'web' || $target eq 'grade'   || $target eq 'answer' ||
 2453: 	    $target eq 'tex' || $target eq 'analyze' || $target eq 'webgrade') {
 2454: 	    my $result = &Apache::lonxml::endredirection();
 2455: 	    my $which = &Apache::lonxml::get_param('which',$parstack,
 2456: 						   $safeeval);
 2457:             if ($which=~/\w/) {
 2458:                 $available_texts{$which} = $result;
 2459:             }
 2460:             my $otherlangs = &Apache::lonxml::get_param('other',$parstack,
 2461:                                                         $safeeval);
 2462:             foreach my $language (split(/\s*\,\s*/,$otherlangs)) {
 2463:                 if ($language=~/\w/) {
 2464:                     $available_texts{$language} = $result;
 2465:                 }
 2466:             }
 2467: 
 2468: 	}
 2469: 	return '';
 2470:     }
 2471: }				# end langauge block specific tags.
 2472: 
 2473: 
 2474: sub start_instructorcomment {
 2475:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2476: 
 2477:     my $result;
 2478: 
 2479:     if ($target eq 'web' || $target eq 'grade'   || $target eq 'answer' ||
 2480: 	$target eq 'tex' || $target eq 'analyze' || $target eq 'webgrade') {
 2481:         $result=($env{'request.role'}=~/^(in|cc|co|au|ca|li)/);
 2482: 	if ( (! $result) or ($env{'form.instructor_comments'} eq 'hide')) {
 2483: 	    my $skip=&Apache::lonxml::get_all_text("/instructorcomment",
 2484: 						   $parser,$style);
 2485: 	    &Apache::lonxml::debug("skipping ahead :$skip: $$parser[-1]");
 2486: 	}
 2487: 	$result='';
 2488:     } elsif ($target eq 'edit') {
 2489: 	$result .=&Apache::edit::tag_start($target,$token);
 2490: 	$result .=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
 2491:     }
 2492:     return $result;
 2493: }
 2494: 
 2495: sub end_instructorcomment {
 2496:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2497:     my $result;
 2498:     if ($target eq "edit") {
 2499: 	$result.= &Apache::edit::tag_end($target,$token,'');
 2500:     }
 2501:     return $result;
 2502: }
 2503: 
 2504: sub start_while {
 2505:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2506: 
 2507:     my $result;
 2508:     if ($target eq 'web' || $target eq 'grade'   || $target eq 'answer' ||
 2509: 	$target eq 'tex' || $target eq 'analyze' || $target eq 'webgrade') {
 2510: 	my $code = $token->[2]->{'condition'};
 2511: 
 2512: 	push( @Apache::structuretags::whileconds, $code);
 2513: 	if (!$Apache::lonxml::default_homework_loaded) {
 2514: 	    &Apache::lonxml::default_homework_load($safeeval);
 2515: 	}
 2516: 	my $result = &Apache::run::run($code,$safeeval);
 2517: 	my $bodytext=&Apache::lonxml::get_all_text("/while",$parser,$style);
 2518: 	push( @Apache::structuretags::whilebody, $bodytext);
 2519: 	push( @Apache::structuretags::whileline, $token->[5]);
 2520: 	&Apache::lonxml::debug("s code $code got -$result-");
 2521: 	if ( $result ) {
 2522: 	    &Apache::lonxml::newparser($parser,\$bodytext);
 2523: 	}
 2524:     } elsif ($target eq 'edit') {
 2525: 	$result .=&Apache::edit::tag_start($target,$token);
 2526: 	$result .=&Apache::edit::text_arg(&mt('Test Condition:'),'condition',
 2527: 					  $token,40);
 2528: 	$result .=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
 2529:     } elsif ($target eq 'modified') {
 2530: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
 2531: 						     $safeeval,'condition');
 2532: 	if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
 2533:     }
 2534:     return $result;
 2535: }
 2536: 
 2537: sub end_while {
 2538:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2539:     my $result;
 2540: 
 2541:     if ($target eq 'web' || $target eq 'grade'   || $target eq 'answer' ||
 2542: 	$target eq 'tex' || $target eq 'analyze' || $target eq 'webgrade') {
 2543: 	my $code = pop(@Apache::structuretags::whileconds);
 2544: 	my $bodytext = pop(@Apache::structuretags::whilebody);
 2545: 	my $line = pop(@Apache::structuretags::whileline);
 2546: 	my $return = &Apache::run::run($code,$safeeval);
 2547: 	my $starttime=time;
 2548: 	my $error=0;
 2549: 	while ($return) {
 2550: 	    if (time-$starttime >
 2551: 		$Apache::lonnet::perlvar{'lonScriptTimeout'}) {
 2552: 		$return = 0; $error=1; next;
 2553: 	    }
 2554: 	    $result.=&Apache::scripttag::xmlparse($bodytext);
 2555: 	    if ($target eq 'grade' || $target eq 'answer' ||
 2556: 		$target eq 'analyze') {
 2557: 		# grade/answer/analyze should produce no output but if we
 2558: 		# are redirecting, the redirecter should know what to do
 2559: 		# with the output
 2560: 		if (!$Apache::lonxml::redirection) { undef($result); }
 2561: 	    }
 2562: 	    $return = &Apache::run::run($code,$safeeval);
 2563: 	}
 2564:         if ($error) {
 2565:             &Apache::lonxml::error(
 2566:                 '<pre>'
 2567:                .&mt('Code ran too long. It ran for more than [_1] seconds.',
 2568:                         $Apache::lonnet::perlvar{'lonScriptTimeout'})
 2569:                .&mt('This occurred while running &lt;while&gt; on line [_1].',
 2570:                         $line)
 2571:                .'</pre>');
 2572:         }
 2573:     } elsif ($target eq "edit") {
 2574: 	$result.= &Apache::edit::tag_end($target,$token,'');
 2575:     }
 2576:     return $result;
 2577: }
 2578: 
 2579: # <randomlist show="1">
 2580: #  <tag1>..</tag1>
 2581: #  <tag2>..</tag2>
 2582: #  <tag3>..</tag3>
 2583: #  ...
 2584: # </randomlist>
 2585: sub start_randomlist {
 2586:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2587:     my $result;
 2588:     if ($target eq 'answer' || $target eq 'grade'   || $target eq 'web' ||
 2589: 	$target eq 'tex'    || $target eq 'analyze' || $target eq 'webgrade') {
 2590: 	my $body= &Apache::lonxml::get_all_text("/randomlist",$parser);
 2591: 	my $b_parser= HTML::LCParser->new(\$body);
 2592: 	$b_parser->xml_mode(1);
 2593: 	$b_parser->marked_sections(1);
 2594: 	my $b_tok;
 2595: 	my @randomlist;
 2596: 	my $list_item;
 2597: 	while($b_tok = $b_parser->get_token() ) {
 2598: 	    if($b_tok->[0] eq 'S') { # start tag
 2599: 		# get content of the tag until matching end tag
 2600: 		# get all text upto the matching tag
 2601: 		# and push the content into @randomlist
 2602: 		$list_item = &Apache::lonxml::get_all_text('/'.$b_tok->[1],
 2603: 							   $b_parser);
 2604: 		$list_item = "$b_tok->[4]"."$list_item"."</$b_tok->[1]>";
 2605: 		push(@randomlist,$list_item);
 2606: 		#  print "<br /><b>START-TAG $b_tok->[1], $b_tok->[4],
 2607:                 #         $list_item</b>";
 2608: 	    }
 2609: 	    if($b_tok->[0] eq 'T') { # text
 2610: 		# what to do with text in between tags?
 2611: 		#  print "<b>TEXT $b_tok->[1]</b><br />";
 2612: 	    }
 2613: 	    # if($b_tok->[0] eq 'E') { # end tag, should not happen
 2614: 	    #  print "<b>END-TAG $b_tok->[1]</b><br />";
 2615: 	    # }
 2616: 	}
 2617: 	if (@randomlist) {
 2618: 	    my @idx_arr = (0 .. $#randomlist);
 2619:             if ($env{'form.code_for_randomlist'}) {
 2620:                 &Apache::structuretags::shuffle(\@idx_arr,$target);
 2621:                 undef($env{'form.code_for_randomlist'});
 2622:             } else {
 2623:                 &Apache::structuretags::shuffle(\@idx_arr);
 2624:             }
 2625: 	    my $bodytext = '';
 2626: 	    my $show=$#randomlist;
 2627: 	    my $showarg=&Apache::lonxml::get_param('show',$parstack,$safeeval);
 2628: 	    $showarg--;
 2629: 	    if ( ($showarg >= 0) && ($showarg < $show) ) { $show = $showarg; }
 2630:             if (($target eq 'analyze') && ($env{'form.check_parts_withrandomlist'})) {
 2631:                 my @currlist;
 2632:                 my $part = $Apache::inputtags::part;
 2633:                 if ($part ne '') {
 2634:                     if (ref($Apache::lonhomework::analyze{'parts_withrandomlist'}) eq 'ARRAY') {
 2635:                         my @currlist = @{$Apache::lonhomework::analyze{'parts_withrandomlist'}};
 2636:                         if (!(grep(/^\Q$part\E$/,@currlist))) {
 2637:                             push(@{$Apache::lonhomework::analyze{'parts_withrandomlist'}},$part);
 2638:                         }
 2639:                     } else {
 2640:                         push(@{$Apache::lonhomework::analyze{'parts_withrandomlist'}},$part);
 2641:                     }
 2642:                 }
 2643:             }
 2644: 	    for my $i (0 .. $show) {
 2645: 		$bodytext .= "$randomlist[ $idx_arr[$i] ]";
 2646: 	    }
 2647: 	    &Apache::lonxml::newparser($parser,\$bodytext);
 2648: 	}
 2649:     } elsif ($target eq 'edit' ) {
 2650: 	$result .=&Apache::edit::tag_start($target,$token);
 2651: 	$result .=&Apache::edit::text_arg('Maximum Tags to Show:','show',
 2652: 					   $token,5);
 2653: 	$result .=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
 2654:     } elsif ($target eq 'modified' ) {
 2655: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
 2656: 						     $safeeval,'show');
 2657: 	if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
 2658:     }
 2659:     return $result;
 2660: }
 2661: 
 2662: sub shuffle {
 2663:     my ($a,$target) = @_;
 2664:     my $i;
 2665:     if (ref($a) eq 'ARRAY' && @$a) {
 2666: 	&Apache::response::pushrandomnumber(undef,$target);
 2667: 	for($i=@$a;--$i;) {
 2668: 	    my $j=int(&Math::Random::random_uniform() * ($i+1));
 2669: 	    next if $i == $j;
 2670: 	    @$a[$i,$j] = @$a[$j,$i];
 2671: 	}
 2672: 	&Apache::response::poprandomnumber();
 2673:     }
 2674: }
 2675: 
 2676: sub end_randomlist {
 2677:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2678:     my $result;
 2679:     if ($target eq 'edit' ) {
 2680: 	$result=&Apache::edit::tag_end($target,$token,
 2681: 				       'End Randomly Parsed Block');
 2682:     }
 2683:     return $result;
 2684: }
 2685: 
 2686: sub ordered_show_check {
 2687:     my $last_part=$Apache::inputtags::partlist[-2];
 2688:     my $in_order=
 2689: 	&Apache::lonnet::EXT('resource.'.$Apache::inputtags::part.'.ordered');
 2690:     my $in_order_show=1;
 2691:     if ($last_part ne '0' && lc($in_order) eq 'yes') {
 2692: 	$in_order_show=&Apache::response::check_status($last_part);
 2693:     }
 2694:     return $in_order_show;
 2695: }
 2696: 
 2697: 
 2698: sub start_startpartmarker {
 2699:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2700:     my $result='';
 2701:     if ($target eq 'edit') {
 2702:         $result=&Apache::edit::tag_start($target,$token);
 2703:         $result.=&mt('Marker for the start of a part. Place end marker below to wrap in-between tags into a new part.').'</td></tr>';
 2704:         $result.=&Apache::edit::end_table();
 2705: 
 2706:     } 
 2707:     return $result;
 2708: }
 2709: 
 2710: sub end_startpartmarker {
 2711:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2712:     my @result;
 2713:     if ($target eq 'edit') { $result[1]='no'; }
 2714:     return @result;
 2715: }
 2716: 
 2717: sub start_endpartmarker {
 2718:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2719:     my $result='';
 2720:     if ($target eq 'edit') {
 2721:         $result=&Apache::edit::tag_start($target,$token);
 2722:         $result.=&mt('Marker for the end of a part. Place start marker above to wrap in-between tags into a new part.').'</td></tr>';
 2723:         $result.=&Apache::edit::end_table();
 2724: 
 2725:     }
 2726:     return $result;
 2727: }
 2728: 
 2729: sub end_endpartmarker {
 2730:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2731:     my @result;
 2732:     if ($target eq 'edit') { $result[1]='no'; }
 2733:     return @result;
 2734: }
 2735: 
 2736: 
 2737: 
 2738: 
 2739: 
 2740: sub start_part {
 2741:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2742:     if (!$Apache::lonxml::metamode) {
 2743: 	&Apache::lonxml::startredirection(); # we'll use redirection to fix up 
 2744: 	                                     # duedates.
 2745:     }
 2746:     my $result='';
 2747:     my $id= &Apache::lonxml::get_id($parstack,$safeeval);
 2748:     $Apache::inputtags::part=$id;
 2749:     push(@Apache::inputtags::partlist,$id);
 2750:     $Apache::inputtags::leniency='';
 2751:     @Apache::inputtags::response=();
 2752:     @Apache::inputtags::previous=();
 2753:     @Apache::inputtags::previous_version=();
 2754:     &Apache::lonhomework::set_show_problem_status(&get_problem_status($id));
 2755:     &Apache::response::reset_params();
 2756: 
 2757:     my $hidden=&Apache::loncommon::check_if_partid_hidden($Apache::inputtags::part);
 2758:     my $newtype=&Apache::lonnet::EXT("resource.$id.type");
 2759:     if ($newtype) { $Apache::lonhomework::type=$newtype; }
 2760:     if ($Apache::lonhomework::type eq 'randomizetry') {
 2761:         my $rndseed=&setup_rndseed($safeeval,$target);
 2762:         if (($target eq 'grade') && &Apache::response::submitted()) {
 2763:             $Apache::lonhomework::results{"resource.$id.rndseed"}=$rndseed;
 2764:         }
 2765:     } elsif (($target eq 'grade') && &Apache::response::submitted()) {
 2766:         $Apache::lonhomework::results{"resource.$id.rndseed"}=$Apache::lonhomework::rawrndseed;
 2767:     }
 2768:     my $in_order_show=&ordered_show_check();
 2769:     my $expression='$external::part=\''.$Apache::inputtags::part.'\';';
 2770:     $expression.='$external::type=\''.$Apache::lonhomework::type.'\';';
 2771:     &Apache::run::run($expression,$safeeval);
 2772: 
 2773:     if ($target eq 'meta') {
 2774: 	my $display=&Apache::lonxml::get_param('display',$parstack,$safeeval);
 2775: 	return &Apache::response::mandatory_part_meta.
 2776: 	       &Apache::response::meta_parameter_write('display','string',$display,'Part Description');
 2777:     } elsif ($target eq 'web' || $target eq 'grade' ||
 2778: 	     $target eq 'answer' || $target eq 'tex') {
 2779: 	if ($hidden || !$in_order_show) {
 2780: 	    my $bodytext=&Apache::lonxml::get_all_text("/part",$parser,$style);
 2781: 	} else {
 2782: 	    my ($status,$accessmsg) = &Apache::lonhomework::check_access($id);
 2783: 	    push (@Apache::inputtags::status,$status);
 2784: 	    my $expression='$external::datestatus="'.$status.'";';
 2785: 	    $expression.='$external::gradestatus="'.$Apache::lonhomework::history{"resource.$id.solved"}.'";';
 2786: 	    &Apache::run::run($expression,$safeeval);
 2787: 	    if ($env{'request.state'} eq 'construct') {
 2788: 		&set_problem_state($Apache::inputtags::part); 
 2789: 	    }
 2790: 	    if (( $status eq 'CLOSED' ) ||
 2791: 		( $status eq 'UNCHECKEDOUT') ||
 2792: 		( $status eq 'NOT_YET_VIEWED') ||
 2793: 		( $status eq 'BANNED') ||
 2794: 		( $status eq 'UNAVAILABLE') ||
 2795: 		( $status eq 'INVALID_ACCESS')) {
 2796: 		my $bodytext=&Apache::lonxml::get_all_text("/part",$parser,
 2797: 							   $style);
 2798: 		if ( $target eq "web" ) {
 2799: 		    $result="<br />".&mt('Part is not open to be viewed. It')." $accessmsg<br />";
 2800: 		} elsif ( $target eq 'tex' ) {
 2801: 		    if (not $env{'form.problem_split'}=~/yes/) {
 2802: 			$result="\\end{minipage}\\vskip 0 mm ".&mt('Part is not open to be viewed. It')." $accessmsg \\\\\\begin{minipage}{\\textwidth}";
 2803: 		    } else {
 2804: 			$result="\\vskip 0 mm ".&mt('Part is not open to be viewed. It')." $accessmsg \\\\";
 2805: 		    }
 2806: 		}
 2807: 	    } else {
 2808: 		if ($target eq 'tex') {
 2809: 		    if (not $env{'form.problem_split'}=~/yes/) {
 2810: 			if ($$tagstack[-2] eq 'td') {
 2811: 			    $result.='\noindent \begin{minipage}{\textwidth}\noindent';
 2812: 			} else {
 2813: 			    $result.='\noindent \end{minipage}\vskip 0 mm \noindent \begin{minipage}{\textwidth}\noindent';
 2814: 			}
 2815: 		    }
 2816: 		    my $weight = &Apache::lonnet::EXT("resource.$id.weight");
 2817: 		    my $allkeys=&Apache::lonnet::metadata($env{'request.uri'},'packages');
 2818: 		    my @allkeys = split(/,/,$allkeys);
 2819: 		    my $allow_print_points = 0;
 2820: 		    foreach my $partial_key (@allkeys) {
 2821: 			if ($partial_key=~m/^part_(.*)$/) {
 2822: 			    if ($1 ne '0') {$allow_print_points=1;}
 2823: 			}
 2824: 		    }
 2825: 		    my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
 2826: 		    if (defined($maxtries) && $maxtries < 0) {
 2827: 			$allow_print_points=0;
 2828: 		    }
 2829: 		    if (lc($env{'course.'.$env{'request.course.id'}.
 2830: 				    '.disableexampointprint'}) eq 'yes') {
 2831: 			$allow_print_points=0;
 2832: 		    }
 2833: 		    if (($Apache::lonhomework::type eq 'exam') && ($allow_print_points)) { 
 2834: 			$result .= '\vskip 10mm\fbox{\textit{'.&mt('[quant,_1,pt,pt]',$weight ).'}}';
 2835: 
 2836: 		    }
 2837: 		} elsif ($target eq 'web') {
 2838:                     if ($status eq 'CAN_ANSWER') {
 2839:                         my $problemstatus = &get_problem_status($Apache::inputtags::part); 
 2840:                         my $probrandomize = &Apache::lonnet::EXT("resource.$Apache::inputtags::partlist[0].type");
 2841:                         my $probrandtries = &Apache::lonnet::EXT("resource.$Apache::inputtags::partlist[0].randomizeontries");
 2842:                         my $num = scalar(@Apache::inputtags::partlist)-1;
 2843:                         if ($probrandomize eq 'randomizetry') {
 2844:                             if (&Apache::lonnet::EXT("resource.$Apache::inputtags::part.type") ne 'randomizetry') {
 2845:                                 $result .= &randomizetry_part_header($problemstatus,'none',$num);
 2846:                             } else {
 2847:                                 my $reqtries = &Apache::lonnet::EXT("resource.$Apache::inputtags::part.randomizeontries");
 2848:                                 if ($probrandtries ne $reqtries) {
 2849:                                     $result .= &randomizetry_part_header($problemstatus,$reqtries,$num);
 2850:                                 }
 2851:                             }
 2852:                         } elsif (&Apache::lonnet::EXT("resource.$Apache::inputtags::part.type") eq 'randomizetry') {
 2853:                             my $reqtries = &Apache::lonnet::EXT("resource.$Apache::inputtags::part.randomizeontries");
 2854:                             $result .= &randomizetry_part_header($problemstatus,$reqtries,$num);
 2855:                         }
 2856:                     }
 2857: 		    $result.='<a name="'.&escape($Apache::inputtags::part).'" ></a>';
 2858: 		}
 2859: 	    }
 2860: 	}
 2861:     } elsif ($target eq 'edit') {
 2862: 	$result.=&Apache::edit::tag_start($target,$token);
 2863: 	$result.=&Apache::edit::text_arg('Part ID:','id',$token).
 2864: 	    &Apache::loncommon::help_open_topic("Part_Tag_Edit_Help").
 2865: 	    '&nbsp;&nbsp;'.
 2866: &Apache::edit::text_arg('Displayed Part Description:','display',$token).
 2867: 		&Apache::edit::end_row().&Apache::edit::start_spanning_row();
 2868:     } elsif ($target eq 'modified') {
 2869: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
 2870: 						     $safeeval,'id','display');
 2871: 	if ($constructtag) {
 2872: 	    #limiting ids to only letters numbers, and space
 2873: 	    $token->[2]->{'id'}=~s/[^A-Za-z0-9 ]//gs;
 2874: 	    $result = &Apache::edit::rebuild_tag($token);
 2875: 	}
 2876:     }
 2877:     return $result;
 2878: }
 2879: 
 2880: sub end_part {
 2881:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 2882:     &Apache::lonxml::debug("in end_part $target ");
 2883:     my $status=$Apache::inputtags::status['-1'];
 2884:     my $hidden=&Apache::loncommon::check_if_partid_hidden($Apache::inputtags::part);
 2885:     my $in_order_show=&ordered_show_check();
 2886:     my $result;
 2887:     if (!$Apache::lonxml::metamode) {
 2888: 	$result = &Apache::lonxml::endredirection(); # started in &start_part
 2889: 	$Apache::lonxml::post_evaluate=0;
 2890:     }
 2891:     if ($target eq 'grade') {
 2892: 	if (($status eq 'CAN_ANSWER' || $Apache::lonhomework::scantronmode) &&
 2893: 	    !$hidden && $in_order_show) {
 2894: 	    $result.=&Apache::inputtags::grade;
 2895: 	} else {
 2896: 	    # move any submission data to .hidden
 2897: 	    &Apache::inputtags::hidealldata($Apache::inputtags::part);
 2898: 	}
 2899:     } elsif (($target eq 'web' || $target eq 'tex') &&
 2900: 	     !$hidden && $in_order_show) {
 2901: 	my $gradestatus=&Apache::inputtags::gradestatus($Apache::inputtags::part,
 2902: 							$target);
 2903: 	if (($Apache::lonhomework::type eq 'exam' && $target eq 'tex') ||
 2904:              ($env{'form.grade_imsexport'})) {
 2905: 	    $gradestatus='';
 2906: 	}
 2907: 	$result.=$gradestatus;
 2908: 	if ($$tagstack[-2] eq 'td' and $target eq 'tex') {$result.='\end{minipage}';} 
 2909:     } elsif ($target eq 'edit') {
 2910: 	$result.=&Apache::edit::end_table();
 2911:     } elsif ($target eq 'modified') {
 2912: 	 $result .= $token->[2];
 2913:     }
 2914:     pop @Apache::inputtags::status;
 2915:     $Apache::inputtags::part='';
 2916:     $Apache::inputtags::leniency='';
 2917:     $Apache::lonhomework::type = $Apache::lonhomework::default_type;
 2918:     return $result;
 2919: }
 2920: 
 2921: sub start_preduedate {
 2922:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2923:     if ($target eq 'web' || $target eq 'grade'    || $target eq 'answer' ||
 2924: 	$target eq 'tex' || $target eq 'webgrade') {
 2925: 	&Apache::lonxml::debug("State in preduedate is ". $Apache::inputtags::status['-1']);
 2926: 	if (!$Apache::lonhomework::scantronmode &&
 2927: 	    $Apache::inputtags::status['-1'] ne 'CAN_ANSWER' &&
 2928: 	    $Apache::inputtags::status['-1'] ne 'CANNOT_ANSWER') {
 2929: 	    &Apache::lonxml::debug("Wha? ". ($Apache::inputtags::status['-1'] ne 'SHOW_ANSWER'));
 2930: 	    &Apache::lonxml::get_all_text("/preduedate",$parser,$style);
 2931: 	}
 2932:     }
 2933:     return '';
 2934: }
 2935: 
 2936: sub end_preduedate {
 2937:     return '';
 2938: }
 2939: 
 2940: # In all the modes where <postanswerdate> text is 
 2941: # displayable,  all we do is eat up the text between the start/stop
 2942: # tags if the conditions are not right to display it.
 2943: sub start_postanswerdate {
 2944:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2945:     my $pav = &Apache::lonnet::allowed('pav', $env{'request.course.id'}) ||
 2946: 	&Apache::lonnet::allowed('pav',
 2947: 			   $env{'request.course.id'}.'/'.$env{'request.course.sec'});
 2948:     if ($target eq 'web' || $target eq 'grade' || $target eq 'webgrade' ||
 2949: 	$target eq 'tex' ) {
 2950: 	if ($Apache::lonhomework::scantronmode ||
 2951: 	    $Apache::inputtags::status['-1'] ne 'SHOW_ANSWER' ||
 2952: 	    (($target eq 'tex') && !$pav)) {
 2953: 	    &Apache::lonxml::get_all_text("/postanswerdate",$parser,$style);
 2954: 	}
 2955:     }
 2956:     return '';
 2957: }
 2958: 
 2959: sub end_postanswerdate {
 2960:     return '';
 2961: }
 2962: 
 2963: sub start_notsolved {
 2964:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2965:     if ($target eq 'web' || $target eq 'grade' || $target eq 'answer' ||
 2966: 	$target eq 'tex' || $target eq 'webgrade') {
 2967: 	my $gradestatus=$Apache::lonhomework::history{"resource.$Apache::inputtags::part.solved"};
 2968: 	&Apache::lonxml::debug("not solved has :$gradestatus:");
 2969: 	if ($gradestatus =~ /^correct/ &&
 2970: 	    &Apache::response::show_answer()) {
 2971: 	    &Apache::lonxml::debug("skipping");
 2972: 	    &Apache::lonxml::get_all_text("/notsolved",$parser,$style);
 2973: 	}
 2974:     }
 2975:     return '';
 2976: }
 2977: 
 2978: sub end_notsolved {
 2979:     return '';
 2980: }
 2981: 
 2982: sub start_solved {
 2983:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2984:     if ($target eq 'web' || $target eq 'grade' || $target eq 'answer' ||
 2985: 	$target eq 'tex') {
 2986: 	my $gradestatus=$Apache::lonhomework::history{"resource.$Apache::inputtags::part.solved"};
 2987: 	if ($gradestatus !~ /^correct/ ||
 2988: 	    !&Apache::response::show_answer()) {
 2989: 	    &Apache::lonxml::get_all_text("/solved",$parser,$style);
 2990: 	}
 2991:     }
 2992:     return '';
 2993: }
 2994: 
 2995: sub end_solved {
 2996:     return '';
 2997: }
 2998: 
 2999: sub start_problemtype {
 3000:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 3001:     my $result;
 3002:     if ($target eq 'web' || $target eq 'grade'   || $target eq 'answer' ||
 3003: 	$target eq 'tex' || $target eq 'analyze' || $target eq 'webgrade') {
 3004: 	my $mode=lc(&Apache::lonxml::get_param('mode',$parstack,$safeeval));
 3005: 	if (!defined($mode)) { $mode='show'; }
 3006: 	my $for=&Apache::lonxml::get_param('for',$parstack,$safeeval);
 3007: 	my $found=0;
 3008: 	foreach my $type (split(',',$for)) {
 3009: 	    if ($Apache::lonhomework::type eq lc($type)) { $found=1; }
 3010: 	}
 3011: 	if ($mode eq 'show' && !$found) {
 3012: 	    &Apache::lonxml::get_all_text("/problemtype",$parser,$style);
 3013: 	}
 3014: 	if ($mode eq 'hide' && $found) {
 3015: 	    &Apache::lonxml::get_all_text("/problemtype",$parser,$style);
 3016: 	}
 3017:     } elsif ($target eq 'edit') {
 3018: 	$result .=&Apache::edit::tag_start($target,$token);
 3019: 	$result.=&Apache::edit::select_arg('Mode:','mode',
 3020: 					   [['show','Show'],
 3021: 					    ['hide','Hide']]
 3022: 					   ,$token);
 3023: 	$result .=&Apache::edit::checked_arg('When used as type(s):','for',
 3024: 					     [ ['exam','Bubblesheet Exam/Quiz Problem'],
 3025: 					       ['survey','Survey'],
 3026:                                                ['surveycred','Survey (with credit)'],
 3027:                                                ['anonsurvey','Anonymous Survey'],
 3028:                                                ['anonsurveycred','Anonymous Survey (with credit)'],
 3029: 					       ['problem','Homework Problem'],
 3030:                                                ['practice','Practice Problem'],
 3031:                                                ['randomizetry','New Randomization Each Try'] ]
 3032: 					     ,$token);
 3033: 	$result .=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
 3034:     } elsif ($target eq 'modified') {
 3035: 	my $constructtag=&Apache::edit::get_new_args($token,$parstack,
 3036: 						     $safeeval,'mode','for');
 3037: 	if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
 3038:     }
 3039:     return $result;
 3040: }
 3041: 
 3042: sub end_problemtype {
 3043:     return '';
 3044: }
 3045: 
 3046: sub start_startouttext {
 3047:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 3048:     my @result=(''.'');
 3049:     if ($target eq 'edit' || $target eq 'modified' ) { @result=('','no'); }
 3050:     
 3051:     my $nesting = 
 3052: 	&Apache::lonxml::set_state('outtext',
 3053: 				   &Apache::lonxml::get_state('outtext')+1);
 3054:     if ($nesting > 1 && $env{'request.state'} eq 'construct') {
 3055: 	&Apache::lonxml::error("Nesting of &lt;startouttext /&gt; not allowed, on line ".$token->[5]);
 3056:     }
 3057:     return (@result);
 3058: }
 3059: 
 3060: sub end_startouttext {
 3061:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 3062:     my $result='';
 3063:     my $text='';
 3064:     if ($target eq 'edit') {
 3065: 	my $areaid = 'homework_edit_'.$Apache::lonxml::curdepth;
 3066: 	$text=&Apache::lonxml::get_all_text("endouttext",$parser,$style);
 3067:         $result.=&Apache::edit::start_table($token)."<tr><td>".&Apache::loncommon::insert_folding_button()
 3068:                  ." ".&mt('Text Block')."</td>"
 3069:                  .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 3070:                  .&Apache::edit::deletelist($target,$token)
 3071:                  .'</span></td>'
 3072: 	         .'<td><span id="math_'.$areaid.'">';
 3073: 	if ($env{'environment.nocodemirror'}) {
 3074: 	    $result.=&Apache::lonhtmlcommon::dragmath_button($areaid,1);
 3075: 	} else {
 3076: 	    $result.='&nbsp;';
 3077: 	}
 3078: 	$result.='</span></td>'
 3079: 		 .'<td>'
 3080: 		 .&Apache::edit::insertlist($target,$token)
 3081: 		 .'</td>'
 3082: 	         .'<td class="LC_edit_problem_latexhelper">' .
 3083: 	         &Apache::loncommon::helpLatexCheatsheet().
 3084: 		 &Apache::edit::end_row().
 3085:                  &Apache::edit::start_spanning_row()."\n".
 3086: 		 &Apache::edit::editfield($token->[1],$text,"",80,8,1);
 3087:     }
 3088:     if ($target eq 'modified') {
 3089: 	$result='<startouttext />'.&Apache::edit::modifiedfield("endouttext",$parser);
 3090:     }
 3091:     if ($target eq 'tex') {
 3092: 	$result .= '\noindent ';
 3093:     }
 3094:     return $result;
 3095: }
 3096: 
 3097: sub start_endouttext {
 3098:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 3099:     my $result='';
 3100:     if ($target eq "edit" ) { $result="</td></tr>".&Apache::edit::end_table()."\n"; }
 3101:     if ($target eq "modified") {
 3102: 	$result='<endouttext />'.
 3103: 	    &Apache::edit::handle_insertafter('startouttext');
 3104:     }
 3105: 
 3106:     my $nesting = 
 3107: 	&Apache::lonxml::set_state('outtext',
 3108: 				   &Apache::lonxml::get_state('outtext')-1);
 3109:     if ($nesting < 0 && $env{'request.state'} eq 'construct') {
 3110: 	&Apache::lonxml::error(" Extraneous &lt;endouttext /&gt; not allowed on line ".$token->[5]);
 3111: 	&Apache::lonxml::set_state('outtext', 0);
 3112:     }
 3113:     return $result;
 3114: }
 3115: 
 3116: sub end_endouttext {
 3117:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 3118:     my @result=('','');
 3119:     if ($target eq "edit" || $target eq 'modified') { @result=('','no'); }
 3120:     return (@result);
 3121: }
 3122: 
 3123: sub delete_startouttext {
 3124:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 3125:     #  my $text=&Apache::lonxml::get_all_text("endouttext",$parser,$style);
 3126:     my $text=$$parser['-1']->get_text("/endouttext");
 3127:     my $ntoken=$$parser['-1']->get_token();
 3128:     &Apache::lonxml::debug("Deleting :$text: and :$ntoken->[0]:$ntoken->[1]:$ntoken->[2]: for startouttext");
 3129:     &Apache::lonxml::end_tag($tagstack,$parstack,$ntoken);
 3130:     # Deleting 2 parallel tag pairs, but we need the numbers later to look like
 3131:     # they did the last time round
 3132:     &Apache::lonxml::increasedepth($ntoken);
 3133:     &Apache::lonxml::decreasedepth($ntoken);
 3134:     return 1;
 3135: }
 3136: 
 3137: sub start_simpleeditbutton {
 3138:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 3139:     my $result='';
 3140:     if (($env{'form.simple_edit_button'} ne 'off') &&
 3141: 	($target eq 'web') &&
 3142:         (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
 3143:         my $url=$env{'request.noversionuri'};
 3144:         $url=~s/\?.*$//;
 3145: 	my ($symb) = &Apache::lonnet::whichuser();
 3146: #       Warning makes more sense and is more important on edit screen
 3147: #       $result='<p class="LC_warning">'
 3148: #              .&mt('Note: it can take up to 10 minutes for changes to take effect for all users.')
 3149: #              .&Apache::loncommon::help_open_topic('Caching')
 3150: #              .'</p>';
 3151:         $result.=&Apache::loncommon::head_subbox(
 3152:                  &Apache::lonhtmlcommon::start_funclist()
 3153:                 .&Apache::lonhtmlcommon::add_item_funclist(
 3154:                      '<a href="'.$url.'/smpedit?symb='.&escape($symb).'">'
 3155:                     .&mt('Edit').'</a>')
 3156:                 .&Apache::lonhtmlcommon::end_funclist());
 3157: 
 3158:     }
 3159:     return $result;
 3160: }
 3161: 
 3162: sub end_simpleeditbutton {
 3163:     return '';
 3164: }
 3165: 
 3166: sub practice_problem_header {
 3167:     return '<h3 class="LC_info">'.&mt('Practice Problem').'</h3>'.
 3168:            '<span class="LC_info">'.&mt('Submissions are not permanently recorded').
 3169:            '</span>';
 3170: }
 3171: 
 3172: sub randomizetry_problem_header {
 3173:     my ($problemstatus,$reqtries) = @_;
 3174:     my ($header,$text);
 3175:     if ($reqtries > 1) {
 3176:         $header = &mt('New Problem Variation After Every [quant,_1,Try,Tries]',$reqtries);
 3177:         if (($problemstatus eq 'no') ||
 3178:             ($problemstatus eq 'no_feedback_ever')) {
 3179:             $text = &mt('A new variation will be generated after every [quant,_1,try,tries], until the tries limit is reached.',$reqtries);
 3180:         } else {
 3181:             $text = &mt('A new variation will be generated after every [quant,_1,try,tries], until correct or tries limit is reached.',$reqtries);
 3182:         }
 3183:     } else {
 3184:         $header = &mt('New Problem Variation Each Try');
 3185:         if (($problemstatus eq 'no') ||
 3186:             ($problemstatus eq 'no_feedback_ever')) {
 3187:             $text = &mt('A new variation will be generated after each try until the tries limit is reached.');
 3188: 
 3189:         } else {
 3190:             $text = &mt('A new variation will be generated after each try until correct or tries limit is reached.');
 3191:         }
 3192:     }
 3193:     return '<h3 class="LC_info">'.$header.'</h3>'.
 3194:            '<span class="LC_info">'.$text.'</span><hr />';
 3195: }
 3196: 
 3197: sub randomizetry_part_header {
 3198:     my ($problemstatus,$reqtries,$num) = @_;
 3199:     my ($header,$text);
 3200:     if ($reqtries eq 'none') {
 3201:         $header = &mt('No Question Variation');
 3202:         $text = &mt('For this question there will no new variation after a try.');
 3203:     } elsif ($reqtries > 1) {
 3204:         $header = &mt('New Question Variation After Every [quant,_1,Try,Tries]',$reqtries);
 3205:         if (($problemstatus eq 'no') ||
 3206:             ($problemstatus eq 'no_feedback_ever')) {
 3207:             $text = &mt('For this question a new variation will be generated after every [quant,_1,try,tries], until the tries limit is reached.',$reqtries);
 3208:         } else {
 3209:             $text = &mt('For this question a new variation will be generated after every [quant,_1,try,tries], until correct or tries limit is reached.',$reqtries);
 3210:         }
 3211:     } else {
 3212:         $header = &mt('New Question Variation For Each Try');
 3213:         if (($problemstatus eq 'no') ||
 3214:             ($problemstatus eq 'no_feedback_ever')) {
 3215:             $text =  &mt('For this question a new variation will be generated after each try until the tries limit is reached.');
 3216:         } else {
 3217:             $text = &mt('For this question a new variation will be generated after each try until correct or tries limit is reached.');
 3218:         }
 3219:     }
 3220:     my $output;
 3221:     if ($num > 1) {
 3222:         $output .= '<hr />';
 3223:     }
 3224:     $output .=  '<h4 class="LC_info">'.$header.'</h4>'.
 3225:                   '<span class="LC_info">'.$text.'</span><br /><br />';
 3226:     return $output;
 3227: }
 3228: 
 3229: 1;
 3230: __END__
 3231: 
 3232: =pod
 3233: 
 3234: =back
 3235: 
 3236: =cut

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