File:  [LON-CAPA] / loncom / homework / structuretags.pm
Revision 1.527: download - view: text, annotated - select for diffs
Mon Jan 19 15:35:53 2015 UTC (9 years, 3 months ago) by goltermann
Branches: MAIN
CVS tags: HEAD
authoring space overhaul
this update tries to improve the user experience of the authoring space.

added codemirror for xml editor and script tags in colorful editor
added possibility to deactivate codemirror in author settings
added dropdown menu to insert problem templates into xml editor (thanks to tobias reinhardt)
added feature of saving current scrollposition on save when editing problems
added possibility to fold blocks in colorful editor, this state will be saved and restored
added shortcuts to create empty problems, html files and directories

and other smaller features and bugfixes

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

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