File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.552: download - view: text, annotated - select for diffs
Sun Feb 22 18:40:18 2015 UTC (9 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bug 6476
 - When target is grade, put rawrndseed returned by &initialize_rndseed()
   in $Apache::lonhomework::rawrndseed so it can be later stored in:
   in %Apache::lonhomework::results

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.552 2015/02/22 18:40:18 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # Copyright for TtHfunc and TtMfunc by Ian Hutchinson. 
   29: # TtHfunc and TtMfunc (the "Code") may be compiled and linked into 
   30: # binary executable programs or libraries distributed by the 
   31: # Michigan State University (the "Licensee"), but any binaries so 
   32: # distributed are hereby licensed only for use in the context
   33: # of a program or computational system for which the Licensee is the 
   34: # primary author or distributor, and which performs substantial 
   35: # additional tasks beyond the translation of (La)TeX into HTML.
   36: # The C source of the Code may not be distributed by the Licensee
   37: # to any other parties under any circumstances.
   38: #
   39: 
   40: =pod
   41: 
   42: =head1 NAME
   43: 
   44: Apache::lonxml
   45: 
   46: =head1 SYNOPSIS
   47: 
   48: XML Parsing Module
   49: 
   50: This is part of the LearningOnline Network with CAPA project
   51: described at http://www.lon-capa.org.
   52: 
   53: 
   54: =head1 SUBROUTINES
   55: 
   56: =cut
   57: 
   58: 
   59: 
   60: package Apache::lonxml; 
   61: use vars 
   62: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $errorcount $warningcount);
   63: use strict;
   64: use LONCAPA;
   65: use HTML::LCParser();
   66: use HTML::TreeBuilder();
   67: use HTML::Entities();
   68: use Safe();
   69: use Safe::Hole();
   70: use Math::Cephes();
   71: use Math::Random();
   72: use Opcode();
   73: use POSIX qw(strftime);
   74: use Time::HiRes qw( gettimeofday tv_interval );
   75: use Symbol();
   76: 
   77: sub register {
   78:   my ($space,@taglist) = @_;
   79:   foreach my $temptag (@taglist) {
   80:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
   81:   }
   82: }
   83: 
   84: sub deregister {
   85:   my ($space,@taglist) = @_;
   86:   foreach my $temptag (@taglist) {
   87:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
   88:     if ($tempspace eq $space) {
   89:       pop(@{ $Apache::lonxml::alltags{$temptag} });
   90:     }
   91:   }
   92:   #&printalltags();
   93: }
   94: 
   95: use Apache::Constants qw(:common);
   96: use Apache::lontexconvert();
   97: use Apache::style();
   98: use Apache::run();
   99: use Apache::londefdef();
  100: use Apache::scripttag();
  101: use Apache::languagetags();
  102: use Apache::edit();
  103: use Apache::inputtags();
  104: use Apache::outputtags();
  105: use Apache::lonnet;
  106: use Apache::File();
  107: use Apache::loncommon();
  108: use Apache::lonfeedback();
  109: use Apache::lonmsg();
  110: use Apache::loncacc();
  111: use Apache::lonmaxima();
  112: use Apache::lonr();
  113: use Apache::lonlocal;
  114: use Apache::lonhtmlcommon();
  115: use Apache::functionplotresponse();
  116: use Apache::lonnavmaps();
  117: 
  118: #====================================   Main subroutine: xmlparse  
  119: 
  120: #debugging control, to turn on debugging modify the correct handler
  121: 
  122: $Apache::lonxml::debug=0;
  123: 
  124: # keeps count of the number of warnings and errors generated in a parse
  125: $warningcount=0;
  126: $errorcount=0;
  127: 
  128: #path to the directory containing the file currently being processed
  129: @pwd=();
  130: 
  131: #these two are used for capturing a subset of the output for later processing,
  132: #don't touch them directly use &startredirection and &endredirection
  133: @outputstack = ();
  134: $redirection = 0;
  135: 
  136: #controls wheter the <import> tag actually does
  137: $import = 1;
  138: @extlinks=();
  139: 
  140: # meta mode is a bit weird only some output is to be turned off
  141: #<output> tag turns metamode off (defined in londefdef.pm)
  142: $metamode = 0;
  143: 
  144: # turns on and of run::evaluate actually derefencing var refs
  145: $evaluate = 1;
  146: 
  147: # data structure for edit mode, determines what tags can go into what other tags
  148: %insertlist=();
  149: 
  150: # stores the list of active tag namespaces
  151: @namespace=();
  152: 
  153: # stores all Scrit Vars displays for later showing
  154: my @script_var_displays=();
  155: 
  156: # a pointer the the Apache request object
  157: $Apache::lonxml::request='';
  158: 
  159: # a problem number counter, and check on ether it is used
  160: $Apache::lonxml::counter=1;
  161: $Apache::lonxml::counter_changed=0;
  162: 
  163: # Part counter hash.   In analysis mode, the
  164: # problems can use this to record which parts increment the counter
  165: # by how much.  The counter subs will maintain this hash via
  166: # their optional part parameters.  Note that the assumption is that
  167: # analysis is done in one request and therefore it is not necessary to
  168: # save this information request-to-request.
  169: 
  170: 
  171: %Apache::lonxml::counters_per_part = ();
  172: 
  173: #internal check on whether to look at style defs
  174: $Apache::lonxml::usestyle=1;
  175: 
  176: #locations used to store the parameter string for style substitutions
  177: $Apache::lonxml::style_values='';
  178: $Apache::lonxml::style_end_values='';
  179: 
  180: #array of ssi calls that need to occur after we are done parsing
  181: @Apache::lonxml::ssi_info=();
  182: 
  183: #should we do the postag variable interpolation
  184: $Apache::lonxml::post_evaluate=1;
  185: 
  186: #a header message to emit in the case of any generated warning or errors
  187: $Apache::lonxml::warnings_error_header='';
  188: 
  189: #  Control whether or not LaTeX symbols should be substituted for their
  190: #  \ style equivalents...this may be turned off e.g. in an verbatim
  191: #  environment.
  192: 
  193: $Apache::lonxml::substitute_LaTeX_symbols = 1; # Starts out on.
  194: 
  195: sub enable_LaTeX_substitutions {
  196:     $Apache::lonxml::substitute_LaTeX_symbols = 1;
  197: }
  198: sub disable_LaTeX_substitutions {
  199:     $Apache::lonxml::substitute_LaTeX_symbols = 0;
  200: }
  201: 
  202: sub xmlend {
  203:     my ($target,$parser)=@_;
  204:     my $mode='xml';
  205:     my $status='OPEN';
  206:     if ($Apache::lonhomework::parsing_a_problem ||
  207: 	$Apache::lonhomework::parsing_a_task ) {
  208: 	$mode='problem';
  209: 	$status=$Apache::inputtags::status[-1]; 
  210:     }
  211:     my $discussion;
  212:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  213: 					   ['LONCAPA_INTERNAL_no_discussion']);
  214:     if (
  215:            (   (!exists($env{'form.LONCAPA_INTERNAL_no_discussion'})) 
  216:             || ($env{'form.LONCAPA_INTERNAL_no_discussion'} ne 'true')
  217:            ) 
  218:         && ($env{'form.inhibitmenu'} ne 'yes')
  219:        ) {
  220:         $discussion=&Apache::lonfeedback::list_discussion($mode,$status);
  221:     }
  222:     if ($target eq 'tex') {
  223: 	$discussion.='<tex>\keephidden{ENDOFPROBLEM}\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\end{document}</tex>';
  224: 	&Apache::lonxml::newparser($parser,\$discussion,'');
  225: 	return '';
  226:     }
  227: 
  228:     return $discussion;
  229: }
  230: 
  231: sub printalltags {
  232:     foreach my $temp (sort(keys(%Apache::lonxml::alltags))) {
  233:         &Apache::lonxml::debug("$temp -- ".
  234:                                join(',',@{ $Apache::lonxml::alltags{$temp} }));
  235:     }
  236: }
  237: 
  238: sub xmlparse {
  239:  my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
  240: 
  241:  &setup_globals($request,$target);
  242:  &Apache::inputtags::initialize_inputtags();
  243:  &Apache::bridgetask::initialize_bridgetask();
  244:  &Apache::outputtags::initialize_outputtags();
  245:  &Apache::edit::initialize_edit();
  246:  &Apache::londefdef::initialize_londefdef();
  247: 
  248: #
  249: # do we have a course style file?
  250: #
  251: 
  252:  if ($env{'request.course.id'} && $env{'request.state'} ne 'construct') {
  253:      my $bodytext=
  254: 	 $env{'course.'.$env{'request.course.id'}.'.default_xml_style'};
  255:      if ($bodytext) {
  256: 	 foreach my $file (split(',',$bodytext)) {
  257: 	     my $location=&Apache::lonnet::filelocation('',$file);
  258: 	     my $styletext=&Apache::lonnet::getfile($location);
  259: 	     if ($styletext ne '-1') {
  260: 		 %style_for_target = (%style_for_target,
  261: 				      &Apache::style::styleparser($target,$styletext));
  262: 	     }
  263: 	 }
  264:      }
  265:  } elsif ($env{'construct.style'}
  266: 	  && ($env{'request.state'} eq 'construct')) {
  267:      my $location=&Apache::lonnet::filelocation('',$env{'construct.style'});
  268:      my $styletext=&Apache::lonnet::getfile($location);
  269:      if ($styletext ne '-1') {
  270: 	 %style_for_target = (%style_for_target,
  271: 			      &Apache::style::styleparser($target,$styletext));
  272:      }
  273:  }
  274: #&printalltags();
  275:  my @pars = ();
  276:  my $pwd=$env{'request.filename'};
  277:  $pwd =~ s:/[^/]*$::;
  278:  &newparser(\@pars,\$content_file_string,$pwd);
  279: 
  280:  my $safeeval = new Safe;
  281:  my $safehole = new Safe::Hole;
  282:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  283: #-------------------- Redefinition of the target in the case of compound target
  284: 
  285:  ($target, my @tenta) = split('&&',$target);
  286: 
  287:  my @stack = ();
  288:  my @parstack = ();
  289:  &initdepth();
  290:  &init_alarm();
  291:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  292: 				   $safeeval,\%style_for_target,1);
  293: 
  294:  if (@stack) {
  295:      &warning(&mt('At end of file some tags were still left unclosed:').
  296: 	      ' <tt>&lt;'.join('&gt;</tt>, <tt>&lt;',reverse(@stack)).
  297: 	      '&gt;</tt>');
  298:  }
  299:  if ($env{'request.uri'}) {
  300:     &writeallows($env{'request.uri'});
  301:  }
  302:  &do_registered_ssi();
  303:  if ($Apache::lonxml::counter_changed) { &store_counter() }
  304: 
  305:  &clean_safespace($safeeval);
  306: 
  307:  if (@script_var_displays) {
  308:      if ($finaloutput =~ m{</body>\s*</html>\s*$}s) {
  309:          my $scriptoutput = join('',@script_var_displays);
  310:          $finaloutput=~s{(</body>\s*</html>)\s*$}{$scriptoutput$1}s;
  311:      } else {
  312:          $finaloutput .= join('',@script_var_displays);
  313:      }
  314:      undef(@script_var_displays);
  315:  }
  316:  &init_state();
  317:  if ($env{'form.return_only_error_and_warning_counts'}) {
  318:      if ($env{'request.filename'}=~/\.(html|htm|xml)$/i) { 
  319:         my $error=&verify_html($content_file_string);
  320:         if ($error) { $errorcount++; }
  321:      }
  322:      return "$errorcount:$warningcount";
  323:  }
  324:  return $finaloutput;
  325: }
  326: 
  327: sub latex_special_symbols {
  328:     my ($string,$where)=@_;
  329:     #
  330:     #  If e.g. in verbatim mode, then don't substitute.
  331:     #  but return original string.
  332:     #
  333:     if (!($Apache::lonxml::substitute_LaTeX_symbols)) {
  334: 	return $string;
  335:     }
  336:     if ($where eq 'header') {
  337: 	$string =~ s/\\/\$\\backslash\$/g; # \  -> $\backslash$ per LaTex line by line pg  10.
  338: 	$string =~ s/(\$|%|\{|\})/\\$1/g;
  339: 	$string=&Apache::lonprintout::character_chart($string);
  340: 	# any & or # leftover should be safe to just escape
  341:         $string=~s/([^\\])\&/$1\\\&/g;
  342:         $string=~s/([^\\])\#/$1\\\#/g;
  343: 	$string =~ s/_/\\_/g;              # _ -> \_
  344: 	$string =~ s/\^/\\\^{}/g;          # ^ -> \^{} 
  345:     } else {
  346: 	$string=~s/\\/\\ensuremath{\\backslash}/g;
  347: 	$string=~s/\\\%|\%/\\\%/g;
  348: 	$string=~s/\\{|{/\\{/g;
  349: 	$string=~s/\\}|}/\\}/g;
  350: 	$string=~s/\\ensuremath\\{\\backslash\\}/\\ensuremath{\\backslash}/g;
  351: 	$string=~s/\\\$|\$/\\\$/g;
  352: 	$string=~s/\\\_|\_/\\\_/g;
  353:         $string=~s/([^\\]|^)(\~|\^)/$1\\$2\\strut /g;
  354: 	$string=~s/(>|<)/\\ensuremath\{$1\}/g; #more or less
  355: 	$string=&Apache::lonprintout::character_chart($string);
  356: 	# any & or # leftover should be safe to just escape
  357: 	$string=~s/\\\&|\&/\\\&/g;
  358: 	$string=~s/\\\#|\#/\\\#/g;
  359:         $string=~s/\|/\$\\mid\$/g;
  360: #single { or } How to escape?
  361:     }
  362:     return $string;
  363: }
  364: 
  365: sub inner_xmlparse {
  366:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target,$start)=@_;
  367:   my $finaloutput = '';
  368:   my $result;
  369:   my $token;
  370:   my $dontpop=0;
  371:   my $startredirection = $Apache::lonxml::redirection;
  372:   while ( $#$pars > -1 ) {
  373:     while ($token = $$pars['-1']->get_token) {
  374:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
  375: 	if ($metamode<1) {
  376: 	    my $text=$token->[1];
  377: 	    if ($token->[0] eq 'C' && $target eq 'tex') {
  378: 		$text = '';
  379: #		$text = '%'.$text."\n";
  380: 	    }
  381: 	    $result.=$text;
  382: 	}
  383:       } elsif (($token->[0] eq 'D')) {
  384: 	if ($metamode<1 && $target eq 'web') {
  385: 	    my $text=$token->[1];
  386: 	    $result.=$text;
  387: 	}
  388:       } elsif ($token->[0] eq 'PI') {
  389: 	if ($metamode<1 && $target eq 'web') {
  390: 	  $result=$token->[2];
  391: 	}
  392:       } elsif ($token->[0] eq 'S') {
  393: 	# add tag to stack
  394: 	push (@$stack,$token->[1]);
  395: 	# add parameters list to another stack
  396: 	push (@$parstack,&parstring($token));
  397: 	&increasedepth($token);
  398: 	if ($Apache::lonxml::usestyle &&
  399: 	    exists($$style_for_target{$token->[1]})) {
  400: 	    $Apache::lonxml::usestyle=0;
  401: 	    my $string=$$style_for_target{$token->[1]}.
  402: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
  403: 	    &Apache::lonxml::newparser($pars,\$string);
  404: 	    $Apache::lonxml::style_values=$$parstack[-1];
  405: 	    $Apache::lonxml::style_end_values=$$parstack[-1];
  406: 	} else {
  407: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  408: 			     $parstack, $pars, $safeeval, $style_for_target);
  409: 	}
  410:       } elsif ($token->[0] eq 'E') {
  411: 	if ($Apache::lonxml::usestyle &&
  412: 	    exists($$style_for_target{'/'."$token->[1]"})) {
  413: 	    $Apache::lonxml::usestyle=0;
  414: 	    my $string=$$style_for_target{'/'.$token->[1]}.
  415: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
  416: 	    &Apache::lonxml::newparser($pars,\$string);
  417: 	    $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
  418: 	    $Apache::lonxml::style_end_values='';
  419: 	    $dontpop=1;
  420: 	} else {
  421: 	    #clear out any tags that didn't end
  422: 	    while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  423: 		my $lasttag=$$stack[-1];
  424: 		if ($token->[1] =~ /^\Q$lasttag\E$/i) {
  425: 		    &Apache::lonxml::warning(&mt('Using tag [_1] on line [_2] as end tag to [_3]','&lt;/'.$token->[1].'&gt;','.$token->[3].','&lt;'.$$stack[-1].'&gt;'));
  426: 		    last;
  427: 		} else {
  428:                     &Apache::lonxml::warning(&mt('Found tag [_1] on line [_2] when looking for [_3] in file.','&lt;/'.$token->[1].'&gt;',$token->[3],'&lt;/'.$$stack[-1].'&gt;'));
  429: 		    &end_tag($stack,$parstack,$token);
  430: 		}
  431: 	    }
  432: 	    $result = &callsub("end_$token->[1]", $target, $token, $stack,
  433: 			       $parstack, $pars,$safeeval, $style_for_target);
  434: 	}
  435:       } else {
  436: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  437:       }
  438:       #evaluate variable refs in result
  439:       if ($Apache::lonxml::post_evaluate &&$result ne "") {
  440: 	  my $extras;
  441: 	  if (!$Apache::lonxml::usestyle) {
  442: 	      $extras=$Apache::lonxml::style_values;
  443: 	  }
  444: 	  if ( $#$parstack > -1 ) {
  445: 	      $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
  446: 	  } else {
  447: 	      $result= &Apache::run::evaluate($result,$safeeval,$extras);
  448:           }
  449:       }
  450:       $Apache::lonxml::post_evaluate=1;
  451: 
  452:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  453: 	  #Style file definitions should be correct
  454: 	  if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
  455: 	      $result=&latex_special_symbols($result);
  456: 	  }
  457:       }
  458: 
  459:       if ($Apache::lonxml::redirection) {
  460: 	$Apache::lonxml::outputstack['-1'] .= $result;
  461:       } else {
  462: 	$finaloutput.=$result;
  463:       }
  464:       $result = '';
  465: 
  466:       if ($token->[0] eq 'E' && !$dontpop) {
  467: 	&end_tag($stack,$parstack,$token);
  468:       }
  469:       $dontpop=0;
  470:     }	
  471:     if ($#$pars > -1) {
  472: 	pop @$pars;
  473: 	pop @Apache::lonxml::pwd;
  474:     }
  475:   }
  476: 
  477:   # if ($target eq 'meta') {
  478:   #   $finaloutput.=&endredirection;
  479:   # }
  480: 
  481:   if ( $start && $target eq 'grade') { &endredirection(); }
  482:   if ( $Apache::lonxml::redirection > $startredirection) {
  483:       while ($Apache::lonxml::redirection > $startredirection) {
  484: 	  $finaloutput .= &endredirection();
  485:       }
  486:   }
  487:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  488:     $finaloutput=&afterburn($finaloutput);
  489:   }
  490:   if ($target eq 'modified') {
  491: # if modfied, handle startpart and endpart
  492:      $finaloutput=~s/\<startpartmarker[^\>]*\>(.*)\<endpartmarker[^\>]*\>/<part>$1<\/part>/gs;
  493:   }	    
  494:   return $finaloutput;
  495: }
  496: 
  497: ## 
  498: ## Looks to see if there is a subroutine defined for this tag.  If so, call it,
  499: ## otherwise do not call it as we do not know what it is.
  500: ##
  501: sub callsub {
  502:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  503:   my $currentstring='';
  504:   my $nodefault;
  505:   {
  506:     my $sub1;
  507:     no strict 'refs';
  508:     my $tag=$token->[1];
  509: # get utterly rid of extended html tags
  510:     if ($tag=~/^x\-/i) { return ''; }
  511:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  512:     if (!$space) {
  513:      	$tag=~tr/A-Z/a-z/;
  514: 	$sub=~tr/A-Z/a-z/;
  515: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  516:     }
  517: 
  518:     my $deleted=0;
  519:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  520:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  521: 					     $parstack,$parser,$safeeval,
  522: 					     $style);
  523:     }
  524:     if (!$deleted) {
  525:       if ($space) {
  526: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
  527: 	$sub1="$space\:\:$sub";
  528: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  529: 					     $parstack,$parser,$safeeval,
  530: 					     $style);
  531:       } else {
  532:           if ($target eq 'tex') {
  533:               # throw away tag name
  534:               return '';
  535:           }
  536: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
  537: 	if ($metamode <1) {
  538: 	  if (defined($token->[4]) && ($metamode < 1)) {
  539: 	    $currentstring = $token->[4];
  540: 	  } else {
  541: 	    $currentstring = $token->[2];
  542: 	  }
  543: 	}
  544:       }
  545:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  546:       if ($currentstring eq '' && $nodefault eq '') {
  547: 	if ($target eq 'edit') {
  548: 	  #&Apache::lonxml::debug("doing default edit for $token->[1]");
  549: 	  if ($token->[0] eq 'S') {
  550: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  551: 	  } elsif ($token->[0] eq 'E') {
  552: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  553: 	  }
  554: 	}
  555:       }
  556:       if ($target eq 'modified' && $nodefault eq '') {
  557: 	  if ($currentstring eq '') {
  558: 	      if ($token->[0] eq 'S') {
  559: 		  $currentstring = $token->[4];
  560: 	      } elsif ($token->[0] eq 'E') {
  561: 		  $currentstring = $token->[2];
  562: 	      } else {
  563: 		  $currentstring = $token->[2];
  564: 	      }
  565: 	  }
  566: 	  if ($token->[0] eq 'S') {
  567: 	      $currentstring.=&Apache::edit::handle_insert();
  568: 	  } elsif ($token->[0] eq 'E') {
  569: 	      $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
  570: 	  }
  571:       }
  572:     }
  573:     use strict 'refs';
  574:   }
  575:   return $currentstring;
  576: }
  577: 
  578: {
  579:     my %state;
  580: 
  581:     sub init_state {
  582: 	undef(%state);
  583:     }
  584:     
  585:     sub set_state {
  586: 	my ($key,$value) = @_;
  587: 	$state{$key} = $value;
  588: 	return $value;
  589:     }
  590:     sub get_state {
  591: 	my ($key) = @_;
  592: 	return $state{$key};
  593:     }
  594: }
  595: 
  596: sub setup_globals {
  597:   my ($request,$target)=@_;
  598:   $Apache::lonxml::request=$request;
  599:   $errorcount=0;
  600:   $warningcount=0;
  601:   $Apache::lonxml::internal_error=0;
  602:   $Apache::lonxml::default_homework_loaded=0;
  603:   $Apache::lonxml::usestyle=1;
  604:   &init_counter();
  605:   &clear_bubble_lines_for_part();
  606:   &init_state();
  607:   &set_state('target',$target);
  608:   @Apache::lonxml::pwd=();
  609:   @Apache::lonxml::extlinks=();
  610:   @script_var_displays=();
  611:   @Apache::lonxml::ssi_info=();
  612:   $Apache::lonxml::post_evaluate=1;
  613:   $Apache::lonxml::warnings_error_header='';
  614:   $Apache::lonxml::substitute_LaTeX_symbols = 1;
  615:   if ($target eq 'meta') {
  616:     $Apache::lonxml::redirection = 0;
  617:     $Apache::lonxml::metamode = 1;
  618:     $Apache::lonxml::evaluate = 1;
  619:     $Apache::lonxml::import = 0;
  620:   } elsif ($target eq 'answer') {
  621:     $Apache::lonxml::redirection = 0;
  622:     $Apache::lonxml::metamode = 1;
  623:     $Apache::lonxml::evaluate = 1;
  624:     $Apache::lonxml::import = 1;
  625:   } elsif ($target eq 'grade') {
  626:     &startredirection(); #ended in inner_xmlparse on exit
  627:     $Apache::lonxml::metamode = 0;
  628:     $Apache::lonxml::evaluate = 1;
  629:     $Apache::lonxml::import = 1;
  630:   } elsif ($target eq 'modified') {
  631:     $Apache::lonxml::redirection = 0;
  632:     $Apache::lonxml::metamode = 0;
  633:     $Apache::lonxml::evaluate = 0;
  634:     $Apache::lonxml::import = 0;
  635:   } elsif ($target eq 'edit') {
  636:     $Apache::lonxml::redirection = 0;
  637:     $Apache::lonxml::metamode = 0;
  638:     $Apache::lonxml::evaluate = 0;
  639:     $Apache::lonxml::import = 0;
  640:   } elsif ($target eq 'analyze') {
  641:     $Apache::lonxml::redirection = 0;
  642:     $Apache::lonxml::metamode = 0;
  643:     $Apache::lonxml::evaluate = 1;
  644:     $Apache::lonxml::import = 1;
  645:   } else {
  646:     $Apache::lonxml::redirection = 0;
  647:     $Apache::lonxml::metamode = 0;
  648:     $Apache::lonxml::evaluate = 1;
  649:     $Apache::lonxml::import = 1;
  650:   }
  651: }
  652: 
  653: sub init_safespace {
  654:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  655:   $safeeval->reval('use LaTeX::Table;');
  656:   $safeeval->deny_only(':dangerous');
  657:   $safeeval->reval('use LONCAPA::LCMathComplex;');
  658:   $safeeval->permit_only(":default");
  659:   $safeeval->permit("entereval");
  660:   $safeeval->permit(":base_math");
  661:   $safeeval->permit("sort");
  662:   $safeeval->permit("time");
  663:   $safeeval->permit("caller");
  664:   $safeeval->deny("rand");
  665:   $safeeval->deny("srand");
  666:   $safeeval->deny(":base_io");
  667:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  668:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
  669:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  670:   $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
  671: 		  '&chem_standard_order');
  672:   $safehole->wrap(\&Apache::response::check_status,$safeeval,'&check_status');
  673:   $safehole->wrap(\&Apache::response::implicit_multiplication,$safeeval,'&implicit_multiplication');
  674: 
  675:   $safehole->wrap(\&Apache::lonmaxima::maxima_eval,$safeeval,'&maxima_eval');
  676:   $safehole->wrap(\&Apache::lonmaxima::maxima_check,$safeeval,'&maxima_check');
  677:   $safehole->wrap(\&Apache::lonmaxima::maxima_cas_formula_fix,$safeeval,
  678: 		  '&maxima_cas_formula_fix');
  679: 
  680:   $safehole->wrap(\&Apache::lonr::r_eval,$safeeval,'&r_eval');
  681:   $safehole->wrap(\&Apache::lonr::Rentry,$safeeval,'&Rentry');
  682:   $safehole->wrap(\&Apache::lonr::Rarray,$safeeval,'&Rarray');
  683:   $safehole->wrap(\&Apache::lonr::r_check,$safeeval,'&r_check');
  684:   $safehole->wrap(\&Apache::lonr::r_cas_formula_fix,$safeeval,
  685:                   '&r_cas_formula_fix');
  686:  
  687:   $safehole->wrap(\&Apache::caparesponse::capa_formula_fix,$safeeval,
  688: 		  '&capa_formula_fix');
  689: 
  690:   $safehole->wrap(\&Apache::lonlocal::locallocaltime,$safeeval,
  691:                   '&locallocaltime');
  692: 
  693:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  694:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  695:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  696:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  697:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  698:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  699:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  700:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  701:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  702:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  703:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  704:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  705:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  706:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  707:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  708:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  709:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  710:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  711:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  712:   
  713:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
  714:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
  715:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
  716:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
  717:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
  718:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
  719:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
  720:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
  721:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
  722:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
  723:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
  724:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
  725:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
  726:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
  727:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
  728:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
  729:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
  730:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
  731:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
  732:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
  733:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
  734:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
  735: 
  736:   $safehole->wrap(\&Math::Cephes::Matrix::mat,$safeeval,'&mat');
  737:   $safehole->wrap(\&Math::Cephes::Matrix::new,$safeeval,
  738: 		  '&Math::Cephes::Matrix::new');
  739:   $safehole->wrap(\&Math::Cephes::Matrix::coef,$safeeval,
  740: 		  '&Math::Cephes::Matrix::coef');
  741:   $safehole->wrap(\&Math::Cephes::Matrix::clr,$safeeval,
  742: 		  '&Math::Cephes::Matrix::clr');
  743:   $safehole->wrap(\&Math::Cephes::Matrix::add,$safeeval,
  744: 		  '&Math::Cephes::Matrix::add');
  745:   $safehole->wrap(\&Math::Cephes::Matrix::sub,$safeeval,
  746: 		  '&Math::Cephes::Matrix::sub');
  747:   $safehole->wrap(\&Math::Cephes::Matrix::mul,$safeeval,
  748: 		  '&Math::Cephes::Matrix::mul');
  749:   $safehole->wrap(\&Math::Cephes::Matrix::div,$safeeval,
  750: 		  '&Math::Cephes::Matrix::div');
  751:   $safehole->wrap(\&Math::Cephes::Matrix::inv,$safeeval,
  752: 		  '&Math::Cephes::Matrix::inv');
  753:   $safehole->wrap(\&Math::Cephes::Matrix::transp,$safeeval,
  754: 		  '&Math::Cephes::Matrix::transp');
  755:   $safehole->wrap(\&Math::Cephes::Matrix::simq,$safeeval,
  756: 		  '&Math::Cephes::Matrix::simq');
  757:   $safehole->wrap(\&Math::Cephes::Matrix::mat_to_vec,$safeeval,
  758: 		  '&Math::Cephes::Matrix::mat_to_vec');
  759:   $safehole->wrap(\&Math::Cephes::Matrix::vec_to_mat,$safeeval,
  760: 		  '&Math::Cephes::Matrix::vec_to_mat');
  761:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
  762: 		  '&Math::Cephes::Matrix::check');
  763:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
  764: 		  '&Math::Cephes::Matrix::check');
  765: 
  766: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
  767: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
  768: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
  769: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
  770: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
  771: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
  772: 
  773:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  774:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  775:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  776:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  777:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  778:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  779:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  780:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  781:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  782:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  783:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  784:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  785:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  786:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  787:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  788:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  789:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  790:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  791:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  792:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  793:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  794:   $safehole->wrap(\&Apache::loncommon::languages,$safeeval,'&languages');
  795:   $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
  796:   $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
  797:   $safehole->wrap(\&Apache::lonnet::logthis,$safeeval,'&LONCAPA_INTERNAL_LOGTHIS');
  798:   $safehole->wrap(\&Apache::inputtags::finalizeawards,$safeeval,'&LONCAPA_INTERNAL_FINALIZEAWARDS');
  799:   $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
  800:   $safehole->wrap(\&Apache::functionplotresponse::fpr_val,$safeeval,'&fpr_val');
  801:   $safehole->wrap(\&Apache::functionplotresponse::fpr_f,$safeeval,'&fpr_f');
  802:   $safehole->wrap(\&Apache::functionplotresponse::fpr_dfdx,$safeeval,'&fpr_dfdx');
  803:   $safehole->wrap(\&Apache::functionplotresponse::fpr_d2fdx2,$safeeval,'&fpr_d2fdx2');
  804:   $safehole->wrap(\&Apache::functionplotresponse::fpr_vectorcoords,$safeeval,'&fpr_vectorcoords');
  805:   $safehole->wrap(\&Apache::functionplotresponse::fpr_objectcoords,$safeeval,'&fpr_objectcoords');
  806:   $safehole->wrap(\&Apache::functionplotresponse::fpr_vectorlength,$safeeval,'&fpr_vectorlength');
  807:   $safehole->wrap(\&Apache::functionplotresponse::fpr_vectorangle,$safeeval,'&fpr_vectorangle');
  808: 
  809: #  use Data::Dumper;
  810: #  $safehole->wrap(\&Data::Dumper::Dumper,$safeeval,'&LONCAPA_INTERNAL_Dumper');
  811: #need to inspect this class of ops
  812: # $safeeval->deny(":base_orig");
  813:   $safeeval->permit("require");
  814:   $safeinit .= ';$external::target="'.$target.'";';
  815:   &Apache::run::run($safeinit,$safeeval);
  816:   my $rawrndseed = &initialize_rndseed($safeeval);
  817:   if ($target eq 'grade') {
  818:       $Apache::lonhomework::rawrndseed = $rawrndseed;
  819:   }
  820: }
  821: 
  822: sub clean_safespace {
  823:     my ($safeeval) = @_;
  824:     delete_package_recurse($safeeval->{Root});
  825: }
  826: 
  827: sub delete_package_recurse {
  828:      my ($package) = @_;
  829:      my @subp;
  830:      {
  831: 	 no strict 'refs';
  832: 	 while (my ($key,$val) = each(%{*{"$package\::"}})) {
  833: 	     if (!defined($val)) { next; }
  834: 	     local (*ENTRY) = $val;
  835: 	     if (defined *ENTRY{HASH} && $key =~ /::$/ &&
  836: 		 $key ne "main::" && $key ne "<none>::")
  837: 	     {
  838: 		 my ($p) = $package ne "main" ? "$package\::" : "";
  839: 		 ($p .= $key) =~ s/::$//;
  840: 		 push(@subp,$p);
  841: 	     }
  842: 	 }
  843:      }
  844:      foreach my $p (@subp) {
  845: 	 delete_package_recurse($p);
  846:      }
  847:      Symbol::delete_package($package);
  848: }
  849: 
  850: sub initialize_rndseed {
  851:     my ($safeeval)=@_;
  852:     my $rndseed;
  853:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
  854:     $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  855:     my $safeinit = '$external::randomseed="'.$rndseed.'";';
  856:     &Apache::lonxml::debug("Setting rndseed to $rndseed");
  857:     &Apache::run::run($safeinit,$safeeval);
  858:     return $rndseed;
  859: }
  860: 
  861: sub default_homework_load {
  862:     my ($safeeval)=@_;
  863:     &Apache::lonxml::debug('Loading default_homework');
  864:     my $default=&Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonIncludes'}.
  865:                                          '/default_homework.lcpm');
  866:     if ($default eq -1) {
  867: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
  868:     } else {
  869: 	&Apache::run::run($default,$safeeval);
  870: 	$Apache::lonxml::default_homework_loaded=1;
  871:     }
  872: }
  873: 
  874: {
  875:     my $alarm_depth;
  876:     sub init_alarm {
  877: 	alarm(0);
  878: 	$alarm_depth=0;
  879:     }
  880: 
  881:     sub start_alarm {
  882: 	if ($alarm_depth<1) {
  883: 	    my $old=alarm($Apache::lonnet::perlvar{'lonScriptTimeout'});
  884: 	    if ($old) {
  885: 		&Apache::lonxml::error("Cancelled an alarm of $old, this shouldn't occur.");
  886: 	    }
  887: 	}
  888: 	$alarm_depth++;
  889:     }
  890: 
  891:     sub end_alarm {
  892: 	$alarm_depth--;
  893: 	if ($alarm_depth<1) { alarm(0); }
  894:     }
  895: }
  896: my $metamode_was;
  897: sub startredirection {
  898:     if (!$Apache::lonxml::redirection) {
  899: 	$metamode_was=$Apache::lonxml::metamode;
  900:     }
  901:     $Apache::lonxml::metamode=0;
  902:     $Apache::lonxml::redirection++;
  903:     push (@Apache::lonxml::outputstack, '');
  904: }
  905: 
  906: sub endredirection {
  907:     if (!$Apache::lonxml::redirection) {
  908: 	&Apache::lonxml::error("Endredirection was called before a startredirection, perhaps you have unbalanced tags. Some debugging information:".join ":",caller);
  909: 	return '';
  910:     }
  911:     $Apache::lonxml::redirection--;
  912:     if (!$Apache::lonxml::redirection) {
  913: 	$Apache::lonxml::metamode=$metamode_was;
  914:     }
  915:     pop @Apache::lonxml::outputstack;
  916: }
  917: sub in_redirection {
  918:     return ($Apache::lonxml::redirection > 0)
  919: }
  920: 
  921: sub end_tag {
  922:   my ($tagstack,$parstack,$token)=@_;
  923:   pop(@$tagstack);
  924:   pop(@$parstack);
  925:   &decreasedepth($token);
  926: }
  927: 
  928: sub initdepth {
  929:   @Apache::lonxml::depthcounter=();
  930:   undef($Apache::lonxml::last_depth_count);
  931: }
  932: 
  933: 
  934: my @timers;
  935: my $lasttime;
  936: # @Apache::lonxml::depthcounter -> count of tags that exist so
  937: #                                  far at each level
  938: # $Apache::lonxml::last_depth_count -> when ascending, need to
  939: # remember the count for the level below the current level (for
  940: # example going from 1_2 -> 1 -> 1_3 need to remember the 2 )
  941: 
  942: sub increasedepth {
  943:   my ($token) = @_;
  944:   push(@Apache::lonxml::depthcounter,$Apache::lonxml::last_depth_count+1);
  945:   undef($Apache::lonxml::last_depth_count);
  946:   my $time;
  947:   if ($Apache::lonxml::debug eq "1") {
  948:       push(@timers,[&gettimeofday()]);
  949:       $time=&tv_interval($lasttime);
  950:       $lasttime=[&gettimeofday()];
  951:   }
  952:   my $spacing='  'x($#Apache::lonxml::depthcounter);
  953:   $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
  954: #  &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time");
  955: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  956: }
  957: 
  958: sub decreasedepth {
  959:   my ($token) = @_;
  960:   if (  $#Apache::lonxml::depthcounter == -1) {
  961:       &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
  962:   }
  963:   $Apache::lonxml::last_depth_count = pop(@Apache::lonxml::depthcounter);
  964: 
  965:   my ($timer,$time);
  966:   if ($Apache::lonxml::debug eq "1") {
  967:       $timer=pop(@timers);
  968:       $time=&tv_interval($lasttime);
  969:       $lasttime=[&gettimeofday()];
  970:   }
  971:   my $spacing='  'x($#Apache::lonxml::depthcounter);
  972:   $Apache::lonxml::curdepth = join('_',@Apache::lonxml::depthcounter);
  973: #  &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time : ".&tv_interval($timer));
  974: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
  975: }
  976: 
  977: sub get_id {
  978:     my ($parstack,$safeeval)=@_;
  979:     my $id= &Apache::lonxml::get_param('id',$parstack,$safeeval);
  980:     if ($env{'request.state'} eq 'construct' && $id =~ /([._]|[^\w\d\s[:punct:]])/) {
  981: 	&error(&mt('ID [_1] contains invalid characters. IDs are only allowed to contain letters, numbers, spaces and -','"<tt>'.$id.'</tt>"'));
  982:     }
  983:     if ($id =~ /^\s*$/) { $id = $Apache::lonxml::curdepth; }
  984:     return $id;
  985: }
  986: 
  987: sub get_all_text_unbalanced {
  988: #there is a copy of this in lonpublisher.pm
  989:     my($tag,$pars)= @_;
  990:     my $token;
  991:     my $result='';
  992:     $tag='<'.$tag.'>';
  993:     while ($token = $$pars[-1]->get_token) {
  994: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  995: 	    if ($token->[0] eq 'T' && $token->[2]) {
  996: 		$result.='<![CDATA['.$token->[1].']]>';
  997: 	    } else {
  998: 		$result.=$token->[1];
  999: 	    }
 1000: 	} elsif ($token->[0] eq 'PI') {
 1001: 	    $result.=$token->[2];
 1002: 	} elsif ($token->[0] eq 'S') {
 1003: 	    $result.=$token->[4];
 1004: 	} elsif ($token->[0] eq 'E')  {
 1005: 	    $result.=$token->[2];
 1006: 	}
 1007: 	if ($result =~ /\Q$tag\E/is) {
 1008: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
 1009: 	    #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
 1010: 	    #&Apache::lonxml::debug('Result is :'.$1);
 1011: 	    $redo=$tag.$redo;
 1012: 	    &Apache::lonxml::newparser($pars,\$redo);
 1013: 	    last;
 1014: 	}
 1015:     }
 1016:     return $result
 1017: 
 1018: }
 1019: 
 1020: #########################################################################
 1021: #                                                                       #
 1022: #           bubble line counter management                              #
 1023: #                                                                       #
 1024: #########################################################################
 1025: 
 1026: =pod
 1027: 
 1028: For bubble grading mode and exam bubble printing mode, the tracking of
 1029: the current 'bubble line number' is stored in the %env element
 1030: 'form.counter', and is modifed and handled by the following routines.
 1031: 
 1032: The value of it is stored in $Apache:lonxml::counter when live and
 1033: stored back to env after done.
 1034: 
 1035: =item &increment_counter($increment, $part_response);
 1036: 
 1037: Increments the internal counter environment variable a specified amount
 1038: 
 1039: Optional Arguments:
 1040:   $increment - amount to increment by (defaults to 1)
 1041:                Also 1 if the value is negative or zero.
 1042:   $part_response - A concatenation of the part and response id
 1043:                    identifying exactly what is being 'answered'.
 1044: 
 1045: 
 1046: =cut
 1047: 
 1048: sub increment_counter {
 1049:     my ($increment, $part_response) = @_;
 1050:     if ($env{'form.grade_noincrement'}) { return; }
 1051:     if (!defined($increment) || $increment le 0) {
 1052: 	$increment = 1;
 1053:     }
 1054:     $Apache::lonxml::counter += $increment;
 1055: 
 1056:     # If the caller supplied the response_id parameter, 
 1057:     # Maintain its counter.. creating if necessary.
 1058: 
 1059:     if (defined($part_response)) {
 1060: 	if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
 1061: 	    $Apache::lonxml::counters_per_part{$part_response} = 0;
 1062: 	}
 1063: 	$Apache::lonxml::counters_per_part{$part_response} += $increment;
 1064: 	my $new_value = $Apache::lonxml::counters_per_part{$part_response};
 1065:     }
 1066: 	
 1067:     $Apache::lonxml::counter_changed=1;
 1068: }
 1069: 
 1070: =pod
 1071: 
 1072: =item &init_counter($increment);
 1073: 
 1074: Initialize the internal counter environment variable
 1075: 
 1076: =cut
 1077: 
 1078: sub init_counter {
 1079:     if ($env{'request.state'} eq 'construct') {
 1080: 	$Apache::lonxml::counter=1;
 1081: 	$Apache::lonxml::counter_changed=1;
 1082:     } elsif (defined($env{'form.counter'})) {
 1083: 	$Apache::lonxml::counter=$env{'form.counter'};
 1084: 	$Apache::lonxml::counter_changed=0;
 1085:     } else {
 1086: 	$Apache::lonxml::counter=1;
 1087: 	$Apache::lonxml::counter_changed=1;
 1088:     }
 1089: }
 1090: 
 1091: sub store_counter {
 1092:     &Apache::lonnet::appenv({'form.counter' => $Apache::lonxml::counter});
 1093:     $Apache::lonxml::counter_changed=0;
 1094:     return '';
 1095: }
 1096: 
 1097: {
 1098:     my $state;
 1099:     sub clear_problem_counter {
 1100: 	undef($state);
 1101: 	&Apache::lonnet::delenv('form.counter');
 1102: 	&Apache::lonxml::init_counter();
 1103: 	&Apache::lonxml::store_counter();
 1104:     }
 1105: 
 1106:     sub remember_problem_counter {
 1107: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
 1108: 	$state = $env{'form.counter'};
 1109:     }
 1110: 
 1111:     sub restore_problem_counter {
 1112: 	if (defined($state)) {
 1113: 	    &Apache::lonnet::appenv({'form.counter' => $state});
 1114: 	}
 1115:     }
 1116:     sub get_problem_counter {
 1117: 	if ($Apache::lonxml::counter_changed) { &store_counter() }
 1118: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
 1119: 	return $env{'form.counter'};
 1120:     }
 1121: }
 1122: 
 1123: =pod
 1124: 
 1125: =item  bubble_lines_for_part(part_response)
 1126: 
 1127: Returns the number of lines required to get a response for
 1128: $part_response (this is just $Apache::lonxml::counters_per_part{$part_response}
 1129: 
 1130: =cut
 1131: 
 1132: sub bubble_lines_for_part {
 1133:     my ($part_response) = @_;
 1134: 
 1135:     if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
 1136: 	return 0;
 1137:     } else {
 1138: 	return $Apache::lonxml::counters_per_part{$part_response};
 1139:     }
 1140: }
 1141: 
 1142: =pod
 1143: 
 1144: =item clear_bubble_lines_for_part
 1145: 
 1146: Clears the hash of bubble lines per part.  If a caller
 1147: needs to analyze several resources this should be called between
 1148: resources to reset the hash for each problem being analyzed.
 1149: 
 1150: =cut
 1151: 
 1152: sub clear_bubble_lines_for_part {
 1153:     undef(%Apache::lonxml::counters_per_part);
 1154: }
 1155: 
 1156: =pod
 1157: 
 1158: =item set_bubble_lines(part_response, value)
 1159: 
 1160: If there is a problem part, that for whatever reason
 1161: requires bubble lines that are not
 1162: the same as the counter increment, it can call this sub during
 1163: analysis to set its hash value explicitly.
 1164: 
 1165: =cut
 1166: 
 1167: sub set_bubble_lines {
 1168:     my ($part_response, $value) = @_;
 1169: 
 1170:     $Apache::lonxml::counters_per_part{$part_response} = $value;
 1171: }
 1172: 
 1173: =pod
 1174: 
 1175: =item get_bubble_line_hash
 1176: 
 1177: Returns the current bubble line hash.  This is assumed to 
 1178: be small so we return a copy
 1179: 
 1180: 
 1181: =cut
 1182: 
 1183: sub get_bubble_line_hash {
 1184:     return %Apache::lonxml::counters_per_part;
 1185: }
 1186: 
 1187: 
 1188: #--------------------------------------------------
 1189: 
 1190: sub get_all_text {
 1191:     my($tag,$pars,$style)= @_;
 1192:     my $gotfullstack=1;
 1193:     if (ref($pars) ne 'ARRAY') {
 1194: 	$gotfullstack=0;
 1195: 	$pars=[$pars];
 1196:     }
 1197:     if (ref($style) ne 'HASH') {
 1198: 	$style={};
 1199:     }
 1200:     my $depth=0;
 1201:     my $token;
 1202:     my $result='';
 1203:     if ( $tag =~ m:^/: ) { 
 1204: 	my $tag=substr($tag,1); 
 1205: 	#&Apache::lonxml::debug("have:$tag:");
 1206: 	my $top_empty=0;
 1207: 	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
 1208: 	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
 1209: 		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
 1210: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
 1211: 		    if ($token->[2]) {
 1212: 			$result.='<![CDATA['.$token->[1].']]>';
 1213: 		    } else {
 1214: 			$result.=$token->[1];
 1215: 		    }
 1216: 		} elsif ($token->[0] eq 'PI') {
 1217: 		    $result.=$token->[2];
 1218: 		} elsif ($token->[0] eq 'S') {
 1219: 		    if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
 1220: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1221: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1222: 		    $result.=$token->[4];
 1223: 		} elsif ($token->[0] eq 'E')  {
 1224: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
 1225: 		    #skip sending back the last end tag
 1226: 		    if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
 1227: 			my $string=
 1228: 			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
 1229: 				$$style{'/'.$token->[1]}.
 1230: 				    $token->[2].
 1231: 					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
 1232: 			&Apache::lonxml::newparser($pars,\$string);
 1233: 			#&Apache::lonxml::debug("reParsing $string");
 1234: 			next;
 1235: 		    }
 1236: 		    if ($depth > -1) {
 1237: 			$result.=$token->[2];
 1238: 		    } else {
 1239: 			$$pars[-1]->unget_token($token);
 1240: 		    }
 1241: 		}
 1242: 	    }
 1243: 	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
 1244: 	    if (($depth >=0) && ($#$pars > 0) ) {
 1245: 		pop(@$pars);
 1246: 		pop(@Apache::lonxml::pwd);
 1247: 	    }
 1248: 	}
 1249: 	if ($top_empty && $depth >= 0) {
 1250: 	    #never found the end tag ran out of text, throw error send back blank
 1251: 	    &error('Never found end tag for &lt;'.$tag.
 1252: 		   '&gt; current string <pre>'.
 1253: 		   &HTML::Entities::encode($result,'<>&"').
 1254: 		   '</pre>');
 1255: 	    if ($gotfullstack) {
 1256: 		my $newstring='</'.$tag.'>'.$result;
 1257: 		&Apache::lonxml::newparser($pars,\$newstring);
 1258: 	    }
 1259: 	    $result='';
 1260: 	}
 1261:     } else {
 1262: 	while ($#$pars > -1) {
 1263: 	    while ($token = $$pars[-1]->get_token) {
 1264: 		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
 1265: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
 1266: 		    ($token->[0] eq 'D')) {
 1267: 		    if ($token->[2]) {
 1268: 			$result.='<![CDATA['.$token->[1].']]>';
 1269: 		    } else {
 1270: 			$result.=$token->[1];
 1271: 		    }
 1272: 		} elsif ($token->[0] eq 'PI') {
 1273: 		    $result.=$token->[2];
 1274: 		} elsif ($token->[0] eq 'S') {
 1275: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) {
 1276: 			$$pars[-1]->unget_token($token); last;
 1277: 		    } else {
 1278: 			$result.=$token->[4];
 1279: 		    }
 1280: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1281: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1282: 		} elsif ($token->[0] eq 'E')  {
 1283: 		    $result.=$token->[2];
 1284: 		}
 1285: 	    }
 1286: 	    if (($#$pars > 0) ) {
 1287: 		pop(@$pars);
 1288: 		pop(@Apache::lonxml::pwd);
 1289: 	    } else { last; }
 1290: 	}
 1291:     }
 1292:     #&Apache::lonxml::debug("Exit:$result:");
 1293:     return $result
 1294: }
 1295: 
 1296: sub newparser {
 1297:   my ($parser,$contentref,$dir) = @_;
 1298:   push (@$parser,HTML::LCParser->new($contentref));
 1299:   $$parser[-1]->xml_mode(1);
 1300:   $$parser[-1]->marked_sections(1);
 1301:   if ( $dir eq '' ) {
 1302:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
 1303:   } else {
 1304:     push (@Apache::lonxml::pwd, $dir);
 1305:   } 
 1306: }
 1307: 
 1308: sub parstring {
 1309:     my ($token) = @_;
 1310:     my (@vars,@values);
 1311:     foreach my $attr (@{$token->[3]}) {
 1312: 	if ($attr!~/\W/) {
 1313: 	    my $val=$token->[2]->{$attr};
 1314: 	    $val =~ s/([\%\@\\\"\'])/\\$1/g;
 1315: 	    $val =~ s/(\$[^\{a-zA-Z_])/\\$1/g;
 1316: 	    $val =~ s/(\$)$/\\$1/;
 1317: 	    #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
 1318: 	    push(@vars,"\$$attr");
 1319: 	    push(@values,"\"$val\"");
 1320: 	}
 1321:     }
 1322:     my $var_init = 
 1323: 	(@vars) ? 'my ('.join(',',@vars).') = ('.join(',',@values).');'
 1324: 	        : '';
 1325:     return $var_init;
 1326: }
 1327: 
 1328: sub extlink {
 1329:     my ($res,$exact)=@_;
 1330:     if (!$exact) {
 1331: 	$res=&Apache::lonnet::hreflocation($Apache::lonxml::pwd[-1],$res);
 1332:     }
 1333:     push(@Apache::lonxml::extlinks,$res);
 1334: }
 1335: 
 1336: sub writeallows {
 1337:     unless ($#extlinks>=0) { return; }
 1338:     my $thisurl = &Apache::lonnet::clutter(shift);
 1339:     if ($env{'httpref.'.$thisurl}) {
 1340: 	$thisurl=$env{'httpref.'.$thisurl};
 1341:     }
 1342:     my $thisdir=$thisurl;
 1343:     $thisdir=~s/\/[^\/]+$//;
 1344:     my %httpref=();
 1345:     foreach (@extlinks) {
 1346:        $httpref{'httpref.'.
 1347:  	        &Apache::lonnet::hreflocation($thisdir,&unescape($_))}=$thisurl;
 1348:     }
 1349:     @extlinks=();
 1350:     &Apache::lonnet::appenv(\%httpref);
 1351: }
 1352: 
 1353: sub register_ssi {
 1354:     my ($url,%form)=@_;
 1355:     push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
 1356:     return '';
 1357: }
 1358: 
 1359: sub do_registered_ssi {
 1360:     foreach my $info (@Apache::lonxml::ssi_info) {
 1361: 	my %form=%{ $info->{'form'}};
 1362: 	my $url=$info->{'url'};
 1363: 	&Apache::lonnet::ssi($url,%form);
 1364:     }
 1365: }
 1366: 
 1367: sub add_script_result {
 1368:     my ($display) = @_;
 1369:     if ($display ne '') {
 1370:         push(@script_var_displays, $display);
 1371:     }
 1372: }
 1373: 
 1374: #
 1375: # Afterburner handles anchors, highlights and links
 1376: #
 1377: sub afterburn {
 1378:     my $result=shift;
 1379:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1380: 					    ['highlight','anchor','link']);
 1381:     if ($env{'form.highlight'}) {
 1382:        foreach (split(/\,/,$env{'form.highlight'})) {
 1383:            my $anchorname=$_;
 1384: 	   my $matchthis=$anchorname;
 1385:            $matchthis=~s/\_+/\\s\+/g;
 1386:            $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1387:        }
 1388:     }
 1389:     if ($env{'form.link'}) {
 1390:        foreach (split(/\,/,$env{'form.link'})) {
 1391:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1392: 	   my $matchthis=$anchorname;
 1393:            $matchthis=~s/\_+/\\s\+/g;
 1394:            $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1395:        }
 1396:     }
 1397:     if ($env{'form.anchor'}) {
 1398:         my $anchorname=$env{'form.anchor'};
 1399: 	my $matchthis=$anchorname;
 1400:         $matchthis=~s/\_+/\\s\+/g;
 1401:         $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1402:         $result.=(<<"ENDSCRIPT");
 1403: <script type="text/javascript">
 1404:     document.location.hash='$anchorname';
 1405: </script>
 1406: ENDSCRIPT
 1407:     }
 1408:     return $result;
 1409: }
 1410: 
 1411: sub storefile {
 1412:     my ($file,$contents)=@_;
 1413:     &Apache::lonnet::correct_line_ends(\$contents);
 1414:     if (my $fh=Apache::File->new('>'.$file)) {
 1415: 	print $fh $contents;
 1416:         $fh->close();
 1417:         return 1;
 1418:     } else {
 1419: 	&warning(&mt('Unable to save file [_1]','<tt>'.$file.'</tt>'));
 1420: 	return 0;
 1421:     }
 1422: }
 1423: 
 1424: sub createnewhtml {
 1425:     my $title=&mt('Title of document goes here');
 1426:     my $body=&mt('Body of document goes here');
 1427:     my $filecontents=(<<SIMPLECONTENT);
 1428: <html>
 1429: <head>
 1430: <title>$title</title>
 1431: </head>
 1432: <body bgcolor="#FFFFFF">
 1433: $body
 1434: </body>
 1435: </html>
 1436: SIMPLECONTENT
 1437:     return $filecontents;
 1438: }
 1439: 
 1440: sub createnewsty {
 1441:   my $filecontents=(<<SIMPLECONTENT);
 1442: <definetag name="">
 1443:     <render>
 1444:        <web></web>
 1445:        <tex></tex>
 1446:     </render>
 1447: </definetag>
 1448: SIMPLECONTENT
 1449:   return $filecontents;
 1450: }
 1451: 
 1452: sub createnewjs {
 1453:     my $filecontents=(<<SIMPLECONTENT);
 1454: <script type="text/javascript" language="Javascript">
 1455: 
 1456: </script>
 1457: SIMPLECONTENT
 1458:     return $filecontents;
 1459: }
 1460: 
 1461: sub verify_html {
 1462:     my ($filecontents)=@_;
 1463:     my ($is_html,$is_xml);
 1464:     if ($filecontents =~/(?:\<|\&lt\;)\?xml[^\<]*\?(?:\>|\&gt\;)/is) {
 1465:         $is_xml = 1;
 1466:     } elsif ($filecontents =~/(?:\<|\&lt\;)html(?:\s+[^\<]+|\s*)(?:\>|\&gt\;)/is) {
 1467:         $is_html = 1;
 1468:     }
 1469:     unless ($is_xml || $is_html) {
 1470:         return &mt('File does not have [_1] or [_2] starting tag','&lt;html&gt;','&lt;?xml ?&gt;');
 1471:     }
 1472:     if ($is_html) {
 1473:         if ($filecontents!~/(?:\<|\&lt\;)\/html(?:\>|\&gt\;)/is) {
 1474:             return &mt('File does not have [_1] ending tag','&lt;html&gt;');
 1475:         }
 1476:         if ($filecontents!~/(?:\<|\&lt\;)(?:body|frameset)[^\<]*(?:\>|\&gt\;)/is) {
 1477:             return &mt('File does not have [_1] or [_2] starting tag','&lt;body&gt;','&lt;frameset&gt;');
 1478:         }
 1479:         if ($filecontents!~/(?:\<|\&lt\;)\/(?:body|frameset)[^\<]*(?:\>|\&gt\;)/is) {
 1480:             return &mt('File does not have [_1] or [_2] ending tag','&lt;body&gt;','&lt;frameset&gt;');
 1481:         }
 1482:     }
 1483:     return '';
 1484: }
 1485: 
 1486: sub renderingoptions {
 1487:     my %langchoices=('' => '');
 1488:     foreach (&Apache::loncommon::languageids()) {
 1489:         if (&Apache::loncommon::supportedlanguagecode($_)) {
 1490:             $langchoices{&Apache::loncommon::supportedlanguagecode($_)}
 1491:                        = &Apache::loncommon::plainlanguagedescription($_);
 1492:         }
 1493:     }
 1494:     my $output;
 1495:     unless ($env{'form.forceedit'}) {
 1496:        $output .=
 1497:            '<span class="LC_nobreak">'.
 1498:            &mt('Language:').' '.
 1499:            &Apache::loncommon::select_form(
 1500:                $env{'form.languages'},
 1501:                'languages',
 1502:                {&Apache::lonlocal::texthash(%langchoices)}).
 1503:            '</span>';
 1504:     }
 1505:     $output .=
 1506:      ' <span class="LC_nobreak">'.
 1507:        &mt('Math Rendering:').' '.
 1508:        &Apache::loncommon::select_form(
 1509:            $env{'form.texengine'},
 1510:            'texengine',
 1511:            {&Apache::lonlocal::texthash
 1512:                (''        => '',
 1513:                 'tth'     => 'tth (TeX to HTML)',
 1514:                 'MathJax' => 'MathJax',
 1515:   		'jsMath'  => 'jsMath',
 1516:                 'mimetex' => 'mimetex (Convert to Images)')}).
 1517:      '</span>';
 1518:     return $output;
 1519: }
 1520: 
 1521: sub inserteditinfo {
 1522:       my ($filecontents,$filetype,$filename,$symb,$itemtitle,$folderpath,$uri,$action) = @_;
 1523:       $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
 1524:       my $xml_help = '';
 1525:       my $initialize='';
 1526:       my $textarea_id = 'filecont';
 1527:       my ($dragmath_button,$deps_button,$context,$cnum,$cdom,$add_to_onload,
 1528:           $add_to_onresize,$init_dragmath);
 1529:       $initialize=&Apache::lonhtmlcommon::spellheader();
 1530:       if ($filetype eq 'html') {
 1531:           if ($env{'request.course.id'}) {
 1532:               $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1533:               $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1534:               if ($uri =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus/\E}) {
 1535:                   $context = 'syllabus';
 1536:               }
 1537:           }
 1538:           if (&Apache::lonhtmlcommon::htmlareabrowser()) {
 1539: 	      my $lang = &Apache::lonhtmlcommon::htmlarea_lang();
 1540:               my %textarea_args = (
 1541:                                     fullpage => 'true',
 1542:                                     dragmath => 'math',
 1543:                                   );
 1544:               $initialize .= &Apache::lonhtmlcommon::htmlareaselectactive(\%textarea_args);
 1545:               if ($context eq 'syllabus') {
 1546:                   $init_dragmath = "editmath_visibility('filecont','none')";
 1547:               }
 1548:           }
 1549:       }
 1550:       $initialize .= (<<FULLPAGE);
 1551: <script type="text/javascript">
 1552: // <![CDATA[
 1553:     function initDocument() {
 1554: 	resize_textarea('$textarea_id','LC_aftertextarea');
 1555:         $init_dragmath
 1556:     }
 1557: // ]]>
 1558: </script>
 1559: FULLPAGE
 1560:       my $textareaclass;
 1561:       if ($filetype eq 'html') {
 1562:           if ($context eq 'syllabus') {
 1563:               $deps_button = &Apache::lonhtmlcommon::dependencies_button()."\n";
 1564:               $initialize .=
 1565:                   &Apache::lonhtmlcommon::dependencycheck_js(undef,&mt('Syllabus'),
 1566:                                                              $uri,undef,
 1567:                                                              "/public/$cdom/$cnum/syllabus").
 1568:                   "\n";
 1569:               if (&Apache::lonhtmlcommon::htmlareabrowser()) {
 1570:                   $textareaclass = 'class="LC_richDefaultOn"';
 1571:               }
 1572:           } elsif ($symb || $folderpath) {
 1573:               $deps_button = &Apache::lonhtmlcommon::dependencies_button()."\n";
 1574:               $initialize .= 
 1575:                   &Apache::lonhtmlcommon::dependencycheck_js($symb,$itemtitle,
 1576:                                                              undef,$folderpath,$uri)."\n";
 1577:           }
 1578:           $dragmath_button = '<span id="math_filecont">'.&Apache::lonhtmlcommon::dragmath_button('filecont',1).'</span>';
 1579:           $initialize .= "\n".&Apache::lonhtmlcommon::dragmath_js('EditMathPopup');
 1580:       }
 1581:       $add_to_onload = 'initDocument();';
 1582:       $add_to_onresize = "resize_textarea('$textarea_id','LC_aftertextarea');";
 1583: 
 1584:       if ($filetype eq 'html') {
 1585:           my $not_author;
 1586:           if ($uri =~ m{^/uploaded/}) {
 1587:               $not_author = 1;
 1588:           }
 1589: 	  $xml_help=&Apache::loncommon::helpLatexCheatsheet(undef,undef,$not_author);
 1590:       }
 1591: 
 1592:       my $titledisplay=&display_title();
 1593:       my %lt=&Apache::lonlocal::texthash('st' => 'Save and Edit',
 1594: 					 'vi' => 'Save and View',
 1595: 					 'dv' => 'Discard Edits and View',
 1596: 					 'un' => 'undo',
 1597: 					 'ed' => 'Edit');
 1598:       my $spelllink = &Apache::lonhtmlcommon::spelllink('xmledit','filecont');
 1599:       my $textarea_events = &Apache::edit::element_change_detection();
 1600:       my $form_events     = &Apache::edit::form_change_detection();
 1601:       my $htmlerror;
 1602:       if ($filetype eq 'html') {
 1603:           $htmlerror=&verify_html($filecontents);
 1604:           if ($htmlerror) {
 1605:               $htmlerror='<span class="LC_error">'.$htmlerror.'</span>';
 1606:           }
 1607:           if (&Apache::lonhtmlcommon::htmlareabrowser()) {
 1608:               unless ($textareaclass) {
 1609:                   $textareaclass = 'class="LC_richDefaultOff"';
 1610:               }
 1611:           }
 1612:       }
 1613:       my $undo;
 1614:       unless ($uri =~ m{^/uploaded/}) {
 1615:           $undo = '<input type="submit" name="Undo" accesskey="u" value="'.$lt{'un'}.'" />'."\n";
 1616:       }
 1617:       my $editfooter=(<<ENDFOOTER);
 1618: $initialize
 1619: <a name="editsection" />
 1620: <form $form_events method="post" name="xmledit" action="$action">
 1621:   <div class="LC_edit_problem_editxml_header">
 1622:     <table class="LC_edit_problem_header_title"><tr><td>
 1623:         $filename
 1624:       </td><td align="right">
 1625:         $xml_help
 1626:       </td></tr>
 1627:     </table>
 1628:     <div class="LC_edit_problem_discards">
 1629:       <input type="submit" name="discardview" accesskey="d" value="$lt{'dv'}" />
 1630:       $undo $htmlerror $deps_button $dragmath_button
 1631:     </div>
 1632:     <div class="LC_edit_problem_saves">
 1633:       <input type="submit" name="savethisfile" accesskey="s" value="$lt{'st'}" />
 1634:       <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
 1635:     </div>
 1636:   </div>
 1637:   <textarea $textarea_events style="width:100%" cols="80" rows="44" name="filecont" id="filecont" $textareaclass>$filecontents</textarea><br />$spelllink
 1638:   <div id="LC_aftertextarea">
 1639:     <br />
 1640:     $titledisplay
 1641:   </div>
 1642: </form>
 1643: ENDFOOTER
 1644:       return ($editfooter,$add_to_onload,$add_to_onresize);;
 1645: }
 1646: 
 1647: sub get_target {
 1648:   my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
 1649:   if ( $env{'request.state'} eq 'published') {
 1650:     if ( defined($env{'form.grade_target'})
 1651: 	 && ($viewgrades == 'F' )) {
 1652:       return ($env{'form.grade_target'});
 1653:     } elsif (defined($env{'form.grade_target'})) {
 1654:       if (($env{'form.grade_target'} eq 'web') ||
 1655: 	  ($env{'form.grade_target'} eq 'tex') ) {
 1656: 	return $env{'form.grade_target'}
 1657:       } else {
 1658: 	return 'web';
 1659:       }
 1660:     } else {
 1661:       return 'web';
 1662:     }
 1663:   } elsif ($env{'request.state'} eq 'construct') {
 1664:     if ( defined($env{'form.grade_target'})) {
 1665:       return ($env{'form.grade_target'});
 1666:     } else {
 1667:       return 'web';
 1668:     }
 1669:   } else {
 1670:     return 'web';
 1671:   }
 1672: }
 1673: 
 1674: sub handler {
 1675:     my $request=shift;
 1676: 
 1677:     my $target=&get_target();
 1678:     $Apache::lonxml::debug=$env{'user.debug'};
 1679:     
 1680:     &Apache::loncommon::content_type($request,'text/html');
 1681:     &Apache::loncommon::no_cache($request);
 1682:     if ($env{'request.state'} eq 'published') {
 1683: 	$request->set_last_modified(&Apache::lonnet::metadata($request->uri,
 1684: 							      'lastrevisiondate'));
 1685:     }
 1686:     # Embedded Flash movies from Camtasia served from https will not display in IE
 1687:     #   if XML config file has expired from cache.    
 1688:     if ($ENV{'SERVER_PORT'} == 443) {
 1689:         if ($request->uri =~ /\.xml$/) {
 1690:             my ($httpbrowser,$clientbrowser) =
 1691:                 &Apache::loncommon::decode_user_agent($request);
 1692:             if ($clientbrowser =~ /^explorer$/i) {
 1693:                 delete $request->headers_out->{'Cache-control'};
 1694:                 delete $request->headers_out->{'Pragma'};
 1695:                 my $expiration = time + 60;
 1696:                 my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime($expiration));
 1697:                 $request->headers_out->set("Expires" => $date);
 1698:             }
 1699:         }
 1700:     }
 1701:     $request->send_http_header;
 1702:     
 1703:     return OK if $request->header_only;
 1704: 
 1705: 
 1706:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1707:     my ($filetype,$breadcrumbtext);
 1708:     if ($file =~ /\.(sty|css|js|txt|tex)$/) {
 1709: 	$filetype=$1;
 1710:     } else {
 1711: 	$filetype='html';
 1712:     }
 1713:     unless ($env{'request.uri'}) {
 1714:         $env{'request.uri'}=$request->uri;
 1715:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1716:                                                 ['todocs']);
 1717:     }
 1718:     my ($cdom,$cnum);
 1719:     if ($env{'request.course.id'}) {
 1720:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1721:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1722:         if ($filetype eq 'html') {
 1723:             if ($request->uri =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus/\E.+$}) {
 1724:                 if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
 1725:                     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1726:                                                             ['editmode']);
 1727:                 }
 1728:             }
 1729:         }
 1730:     }
 1731:     if ($filetype eq 'sty') {
 1732:         $breadcrumbtext = 'Style File Editor';
 1733:     } elsif ($filetype eq 'js') {
 1734:         $breadcrumbtext = 'Javascript Editor';
 1735:     } elsif ($filetype eq 'css') {
 1736:         $breadcrumbtext = 'CSS Editor';
 1737:     } elsif ($filetype eq 'txt') {
 1738:         $breadcrumbtext = 'Text Editor';
 1739:     } elsif ($filetype eq 'tex') {
 1740:         $breadcrumbtext = 'TeX Editor';
 1741:     } else {
 1742:         $breadcrumbtext = 'HTML Editor';
 1743:     }
 1744: 
 1745: #
 1746: # Edit action? Save file.
 1747: #
 1748:     if (!($env{'request.state'} eq 'published')) {
 1749: 	if ($env{'form.savethisfile'} || $env{'form.viewmode'} || $env{'form.Undo'}) {
 1750: 	    my $html_file=&Apache::lonnet::getfile($file);
 1751: 	    my $error = &Apache::lonhomework::handle_save_or_undo($request, \$html_file, \$env{'form.filecont'});
 1752:             if ($env{'form.savethisfile'}) {
 1753:                 $env{'form.editmode'}='Edit'; #force edit mode
 1754:             }
 1755: 	}
 1756:     }
 1757:     my $inhibit_menu;
 1758:     my %mystyle;
 1759:     my $result = '';
 1760:     my $filecontents=&Apache::lonnet::getfile($file);
 1761:     if ($filecontents eq -1) {
 1762: 	my $start_page=&Apache::loncommon::start_page('File Error');
 1763: 	my $end_page=&Apache::loncommon::end_page();
 1764:         my $errormsg='<p class="LC_error">'
 1765:                     .&mt('File not found: [_1]'
 1766:                         ,'<span class="LC_filename">'.$file.'</span>')
 1767:                     .'</p>';
 1768: 	$result=(<<ENDNOTFOUND);
 1769: $start_page
 1770: $errormsg
 1771: $end_page
 1772: ENDNOTFOUND
 1773:         $filecontents='';
 1774: 	if ($env{'request.state'} ne 'published') {
 1775: 	    if ($filetype eq 'sty') {
 1776: 		$filecontents=&createnewsty();
 1777:             } elsif ($filetype eq 'js') {
 1778:                 $filecontents=&createnewjs();
 1779:             } elsif ($filetype ne 'css' && $filetype ne 'txt' && $filetype ne 'tex') {
 1780: 		$filecontents=&createnewhtml();
 1781: 	    }
 1782: 	    $env{'form.editmode'}='Edit'; #force edit mode
 1783: 	}
 1784:     } else {
 1785: 	unless ($env{'request.state'} eq 'published') {
 1786: 	    if ($filecontents=~/BEGIN LON-CAPA Internal/) {
 1787: 		&Apache::lonxml::error(&mt('This file appears to be a rendering of a LON-CAPA resource. If this is correct, this resource will act very oddly and incorrectly.'));
 1788: 	    }
 1789: #
 1790: # we are in construction space, see if edit mode forced
 1791:             &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1792: 						    ['editmode']);
 1793: 	}
 1794: 	if (!$env{'form.editmode'} || $env{'form.viewmode'} || $env{'form.discardview'}) {
 1795:             if ($filetype eq 'html' || $filetype eq 'sty') {
 1796: 	        &Apache::structuretags::reset_problem_globals();
 1797: 	        $result = &Apache::lonxml::xmlparse($request,$target,
 1798:                                                     $filecontents,'',%mystyle);
 1799: 	    # .html files may contain <problem> or <Task> need to clean
 1800: 	    # up if it did
 1801: 	        &Apache::structuretags::reset_problem_globals();
 1802: 	        &Apache::lonhomework::finished_parsing();
 1803:             } elsif ($filetype eq 'tex') {
 1804:                 $result = &Apache::lontexconvert::converted(\$filecontents,
 1805:                               $env{'form.texengine'});
 1806:                 if ($env{'form.return_only_error_and_warning_counts'}) {
 1807:                     $result = "$errorcount:$warningcount";
 1808:                 }
 1809:             } else {
 1810:                 $result = $filecontents;
 1811:             }
 1812: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1813: 						    ['rawmode']);
 1814: 	    if ($env{'form.rawmode'}) { $result = $filecontents; }
 1815:             if (($env{'request.state'} eq 'construct') &&
 1816:                 (($filetype eq 'css') || ($filetype eq 'js')) && ($ENV{'HTTP_REFERER'})) {
 1817:                 if ($ENV{'HTTP_REFERER'} =~ m{^https?\://[^\/]+/priv/$LONCAPA::match_domain/$LONCAPA::match_username/[^\?]+\.(x?html?|swf)(|\?)[^\?]*$}) {
 1818:                     $inhibit_menu = 1;
 1819:                 }
 1820:             }
 1821:             if (($filetype ne 'html') && 
 1822:                 (!$env{'form.return_only_error_and_warning_counts'}) &&
 1823:                 (!$inhibit_menu)) {
 1824:                 my $nochgview = 1;
 1825:                 my $controls = '';
 1826:                     if ($env{'request.state'} eq 'construct') {
 1827:                         $controls = &Apache::loncommon::head_subbox(
 1828:                                         &Apache::loncommon::CSTR_pageheader()
 1829:                                        .&Apache::londefdef::edit_controls($nochgview));
 1830:                     }
 1831:                 if ($filetype ne 'sty' && $filetype ne 'tex') {
 1832:                     $result =~ s/</&lt;/g;
 1833:                     $result =~ s/>/&gt;/g;
 1834:                     $result = '<table class="LC_sty_begin">'.
 1835:                               '<tr><td><b><pre>'.$result.
 1836:                               '</pre></b></td></tr></table>';
 1837:                 }
 1838:                 my $brcrum;
 1839:                 if ($env{'request.state'} eq 'construct') {
 1840:                     $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
 1841:                                 'text' => 'Authoring Space'},
 1842:                                {'href' => '',
 1843:                                 'text' => $breadcrumbtext}];
 1844:                 } else {
 1845:                     $brcrum = ''; # FIXME: Where are we?
 1846:                 }
 1847:                 my %options = ('bread_crumbs' => $brcrum,
 1848:                                'bgcolor'      => '#FFFFFF');
 1849:                 $result =
 1850:                     &Apache::loncommon::start_page(undef,undef,\%options)
 1851:                    .$controls
 1852:                    .$result
 1853:                    .&Apache::loncommon::end_page();
 1854:             }
 1855:         }
 1856:     }
 1857: 
 1858: #
 1859: # Edit action? Insert editing commands
 1860: #
 1861:     unless (($env{'request.state'} eq 'published') || ($inhibit_menu)) {
 1862: 	if ($env{'form.editmode'} && (!($env{'form.viewmode'})) && (!($env{'form.discardview'})))
 1863: 	{
 1864:             my ($displayfile,$url,$symb,$itemtitle,$action);
 1865: 	    $displayfile=$request->uri;
 1866:             if ($request->uri =~ m{^/uploaded/}) {
 1867:                 if ($env{'request.course.id'}) {
 1868:                     if ($request->uri =~ m{^\Q/uploaded/$cdom/$cnum/supplemental/\E}) {
 1869:                         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1870:                                                                 ['folderpath','title']);
 1871:                     } elsif ($request->uri =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus/\E(.+)$}) {
 1872:                         my $filename = $1;
 1873:                         if ($1 eq 'loncapa.html') {
 1874:                             $displayfile = &mt('Syllabus (minimal template)');
 1875:                             $action = $request->uri.'?forceedit=1';
 1876:                         } else {
 1877:                             $displayfile = &mt('Syllabus file: [_1]',$1);
 1878:                         }
 1879:                         $itemtitle = &mt('Syllabus');
 1880:                     }
 1881:                 }
 1882:                 unless ($itemtitle) {
 1883:                     ($symb,$itemtitle,$displayfile) = 
 1884:                         &get_courseupload_hierarchy($request->uri,
 1885:                                                     $env{'form.folderpath'},
 1886:                                                     $env{'form.title'});
 1887:                 }
 1888:             } else {
 1889: 	        $displayfile=~s/^\/[^\/]*//;
 1890:             }
 1891: 
 1892: 	    my ($edit_info, $add_to_onload, $add_to_onresize)=
 1893: 		&inserteditinfo($filecontents,$filetype,$displayfile,$symb,
 1894:                                 $itemtitle,$env{'form.folderpath'},$request->uri,$action);
 1895: 
 1896: 	    my %options = 
 1897: 		('add_entries' =>
 1898:                    {'onresize'     => $add_to_onresize,
 1899:                     'onload'       => $add_to_onload,   });
 1900:             my $header;
 1901:             if ($env{'request.state'} eq 'construct') {
 1902:                 $options{'bread_crumbs'} = [{
 1903:                             'href' => &Apache::loncommon::authorspace($request->uri),
 1904:                             'text' => 'Authoring Space'},
 1905:                            {'href' => '',
 1906:                             'text' => $breadcrumbtext}];
 1907:                 $header = &Apache::loncommon::head_subbox(
 1908:                               &Apache::loncommon::CSTR_pageheader());
 1909:             }
 1910: 	    my $js =
 1911: 		&Apache::edit::js_change_detection().
 1912: 		&Apache::loncommon::resize_textarea_js();
 1913: 	    my $start_page = &Apache::loncommon::start_page(undef,$js,
 1914: 							    \%options);
 1915:             $result = $start_page
 1916:                      .$header
 1917:                      .&Apache::lonxml::message_location()
 1918:                      .$edit_info
 1919:                      .&Apache::loncommon::end_page();
 1920:         }
 1921:     }
 1922:     if ($filetype eq 'html') { &writeallows($request->uri); }
 1923: 
 1924:     &Apache::lonxml::add_messages(\$result);
 1925:     $request->print($result);
 1926:     
 1927:     return OK;
 1928: }
 1929: 
 1930: sub display_title {
 1931:     my $result;
 1932:     if ($env{'request.state'} eq 'construct') {
 1933: 	my $title=&Apache::lonnet::gettitle();
 1934: 	if (!defined($title) || $title eq '') {
 1935: 	    $title = $env{'request.filename'};
 1936: 	    $title = substr($title, rindex($title, '/') + 1);
 1937: 	}
 1938:         $result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA "
 1939:                   .&mt('Authoring Space')."';</script>";
 1940:     }
 1941:     return $result;
 1942: }
 1943: 
 1944: sub get_courseupload_hierarchy {
 1945:     my ($url,$folderpath,$title) = @_;
 1946:     my ($symb,$itemtitle,$displaypath);
 1947:     if ($env{'request.course.id'}) {
 1948:         if ($folderpath =~ /^supplemental/) {
 1949:             my @folders = split(/\&/,$folderpath);
 1950:             my @pathitems;
 1951:             while (@folders) {
 1952:                 my $folder=shift(@folders);
 1953:                 my $foldername=shift(@folders);
 1954:                 $foldername =~ s/\:(\d*)\:(\w*)\:(\w*):(\d*)\:?(\d*)$//;
 1955:                 push(@pathitems,&unescape($foldername));
 1956:             }
 1957:             if ($title) {
 1958:                 push(@pathitems,&unescape($title));
 1959:             }
 1960:             $displaypath = join(' &raquo; ',@pathitems);
 1961:         } else {
 1962:             $symb = &Apache::lonnet::symbread($url);
 1963:             my ($map,$id,$res)=&Apache::lonnet::decode_symb($symb);
 1964:             my $navmap=Apache::lonnavmaps::navmap->new;
 1965:             if (ref($navmap)) {
 1966:                 my $res = $navmap->getBySymb($symb);
 1967:                 if (ref($res)) {
 1968:                     my @pathitems =
 1969:                         &Apache::loncommon::get_folder_hierarchy($navmap,$map,1);
 1970:                     $itemtitle = $res->compTitle();
 1971:                     push(@pathitems,$itemtitle);
 1972:                     $displaypath = join(' &raquo; ',@pathitems);
 1973:                 }
 1974:             }
 1975:         }
 1976:     }
 1977:     return ($symb,$itemtitle,$displaypath);
 1978: }
 1979: 
 1980: sub debug {
 1981:     if ($Apache::lonxml::debug eq "1") {
 1982: 	$|=1;
 1983: 	my $request=$Apache::lonxml::request;
 1984: 	if (!$request) {
 1985: 	    eval { $request=Apache->request; };
 1986: 	}
 1987: 	if (!$request) {
 1988: 	    eval { $request=Apache2::RequestUtil->request; };
 1989: 	}
 1990: 	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
 1991: 	#&Apache::lonnet::logthis($_[0]);
 1992:     }
 1993: }
 1994: 
 1995: sub show_error_warn_msg {
 1996:     if (($env{'request.filename'} eq 
 1997:          $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/lib/templates/simpleproblem.problem') &&
 1998:         (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
 1999: 	return 1;
 2000:     }
 2001:     return (($Apache::lonxml::debug eq 1) ||
 2002: 	    ($env{'request.state'} eq 'construct') ||
 2003: 	    ($Apache::lonhomework::browse eq 'F'
 2004: 	     &&
 2005: 	     $env{'form.show_errors'} eq 'on'));
 2006: }
 2007: 
 2008: sub error {
 2009:     my @errors = @_;
 2010: 
 2011:     $errorcount++;
 2012: 
 2013:     $Apache::lonxml::internal_error=1;
 2014: 
 2015:     if (defined($Apache::inputtags::part)) {
 2016: 	if ( @Apache::inputtags::response ) {
 2017: 	    push(@errors,
 2018: 		 &mt("This error occurred while processing response [_1] in part [_2]",
 2019: 		     $Apache::inputtags::response[-1],
 2020: 		     $Apache::inputtags::part));
 2021: 	} else {
 2022: 	    push(@errors,
 2023: 		 &mt("This error occurred while processing part [_1]",
 2024: 		     $Apache::inputtags::part));
 2025: 	}
 2026:     }
 2027: 
 2028:     if ( &show_error_warn_msg() ) {
 2029: 	# If printing in construction space, put the error inside <pre></pre>
 2030: 	push(@Apache::lonxml::error_messages,
 2031: 	     $Apache::lonxml::warnings_error_header
 2032:              .'<div class="LC_error">'
 2033:              .'<b>'.&mt('ERROR:').' </b>'.join("<br />\n",@errors)
 2034:              ."</div>\n");
 2035: 	$Apache::lonxml::warnings_error_header='';
 2036:     } else {
 2037: 	my $errormsg;
 2038: 	my ($symb)=&Apache::lonnet::symbread();
 2039: 	if ( !$symb ) {
 2040: 	    #public or browsers
 2041: 	    $errormsg=&mt("An error occurred while processing this resource. The author has been notified.");
 2042: 	}
 2043: 	my $host=$Apache::lonnet::perlvar{'lonHostID'};
 2044: 	push(@errors,
 2045:         &mt("The error occurred on host [_1]",
 2046:              "<tt>$host</tt>"));
 2047: 
 2048: 	my $msg = join('<br />', @errors);
 2049: 
 2050: 	#notify author
 2051: 	&Apache::lonmsg::author_res_msg($env{'request.filename'},$msg);
 2052: 	#notify course
 2053: 	if ( $symb && $env{'request.course.id'} ) {
 2054: 	    my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2055: 	    my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2056: 	    my (undef,%users)=&Apache::lonmsg::decide_receiver(undef,0,1,1,1);
 2057: 	    my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
 2058:             my $baseurl = &Apache::lonnet::clutter($declutter);
 2059: 	    my @userlist;
 2060: 	    foreach (keys(%users)) {
 2061: 		my ($user,$domain) = split(/:/, $_);
 2062: 		push(@userlist,"$user:$domain");
 2063: 		my $key=$declutter.'_'.$user.'_'.$domain;
 2064: 		my %lastnotified=&Apache::lonnet::get('nohist_xmlerrornotifications',
 2065: 						      [$key],
 2066: 						      $cdom,$cnum);
 2067: 		my $now=time;
 2068: 		if ($now-$lastnotified{$key}>86400) {
 2069:                     my $title = &Apache::lonnet::gettitle($symb);
 2070:                     my $sentmessage;
 2071: 		    &Apache::lonmsg::user_normal_msg($user,$domain,
 2072: 		        "Error [$title]",$msg,'',$baseurl,'','',
 2073:                         \$sentmessage,$symb,$title,1);
 2074: 		    &Apache::lonnet::put('nohist_xmlerrornotifications',
 2075: 					 {$key => $now},
 2076: 					 $cdom,$cnum);		
 2077: 		}
 2078: 	    }
 2079: 	    if ($env{'request.role.adv'}) {
 2080: 		$errormsg=&mt("An error occurred while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
 2081: 	    } else {
 2082: 		$errormsg=&mt("An error occurred while processing this resource. The instructor has been notified.");
 2083: 	    }
 2084: 	}
 2085: 	push(@Apache::lonxml::error_messages,"<span class=\"LC_warning\">$errormsg</span><br />");
 2086:     }
 2087: }
 2088: 
 2089: sub warning {
 2090:     $warningcount++;
 2091:   
 2092:     if ($env{'form.grade_target'} ne 'tex') {
 2093: 	if ( &show_error_warn_msg() ) {
 2094: 	    push(@Apache::lonxml::warning_messages,
 2095: 		 $Apache::lonxml::warnings_error_header
 2096:                 .'<div class="LC_warning">'
 2097:                 .&mt('[_1]W[_2]ARNING','<b>','</b>')."<b>:</b> ".join('<br />',@_)
 2098:                 ."</div>\n"
 2099:                 );
 2100: 	    $Apache::lonxml::warnings_error_header='';
 2101: 	}
 2102:     }
 2103: }
 2104: 
 2105: sub info {
 2106:     if ($env{'form.grade_target'} ne 'tex' 
 2107: 	&& $env{'request.state'} eq 'construct') {
 2108: 	push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
 2109:     }
 2110: }
 2111: 
 2112: sub message_location {
 2113:     return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
 2114: }
 2115: 
 2116: sub add_messages {
 2117:     my ($msg)=@_;
 2118:     my $result=join(' ',
 2119: 		    @Apache::lonxml::info_messages,
 2120: 		    @Apache::lonxml::error_messages,
 2121: 		    @Apache::lonxml::warning_messages);
 2122:     undef(@Apache::lonxml::info_messages);
 2123:     undef(@Apache::lonxml::error_messages);
 2124:     undef(@Apache::lonxml::warning_messages);
 2125:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
 2126:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
 2127: }
 2128: 
 2129: sub get_param {
 2130:     my ($param,$parstack,$safeeval,$context,$case_insensitive, $noelide) = @_;
 2131: 
 2132:     if ( ! $context ) { $context = -1; }
 2133:     my $args ='';
 2134:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 2135:     if ( ! $Apache::lonxml::usestyle ) {
 2136: 	$args=$Apache::lonxml::style_values.$args;
 2137:     }
 2138: 
 2139: 
 2140:     if ($noelide) {
 2141: #	$args =~ s/\\'/'/g;
 2142: 	$args =~ s/'\$/'\\\$/g;
 2143:     }
 2144: 
 2145:     if ( ! $args ) { return undef; }
 2146:     if ( $case_insensitive ) {
 2147: 	if ($args =~ s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei) {
 2148: 
 2149: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 2150:                                      $safeeval); #'
 2151: 	} else {
 2152: 	    return undef;
 2153: 	}
 2154:     } else {
 2155: 	if ( $args =~ /my .*\$\Q$param\E[,\)]/ ) {
 2156: 	    
 2157: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 2158:                                      $safeeval); #'
 2159: 	} else {
 2160: 	    return undef;
 2161: 	}
 2162:     }
 2163: }
 2164: 
 2165: sub get_param_var {
 2166:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 2167:   if ( ! $context ) { $context = -1; }
 2168:   my $args ='';
 2169:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 2170:   if ( ! $Apache::lonxml::usestyle ) {
 2171:       $args=$Apache::lonxml::style_values.$args;
 2172:   }
 2173:   &Apache::lonxml::debug("Args are $args param is $param");
 2174:   if ($case_insensitive) {
 2175:       if (! ($args=~s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei)) {
 2176: 	  return undef;
 2177:       }
 2178:   } elsif ( $args !~ /my .*\$\Q$param\E[,\)]/ ) { return undef; }
 2179:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 2180:   &Apache::lonxml::debug("first run is $value");
 2181:   if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
 2182:       &Apache::lonxml::debug("doing second");
 2183:       my @result=&Apache::run::run("return $value",$safeeval,1);
 2184:       if (!defined($result[0])) {
 2185: 	  return $value
 2186:       } else {
 2187: 	  if (wantarray) { return @result; } else { return $result[0]; }
 2188:       }
 2189:   } else {
 2190:     return $value;
 2191:   }
 2192: }
 2193: 
 2194: sub register_insert_xml {
 2195:     my $parser = HTML::LCParser->new($Apache::lonnet::perlvar{'lonTabDir'}
 2196: 				     .'/insertlist.xml');
 2197:     my ($tagnum,$in_help)=(0,0);
 2198:     my @alltags;
 2199:     my $tag;
 2200:     while (my $token = $parser->get_token()) {
 2201: 	if ($token->[0] eq 'S') {
 2202: 	    my $key;
 2203: 	    if ($token->[1] eq 'tag') {
 2204: 		$tag = $token->[2]{'name'};
 2205:                 if (defined($tag)) {
 2206: 		    $insertlist{$tagnum.'.tag'} = $tag;
 2207: 		    $insertlist{$tag.'.num'}   = $tagnum;
 2208: 		    push(@alltags,$tag);
 2209:                 }
 2210: 	    } elsif ($in_help && $token->[1] eq 'file') {
 2211: 		$key = $tag.'.helpfile';
 2212: 	    } elsif ($in_help && $token->[1] eq 'description') {
 2213: 		$key = $tag.'.helpdesc';
 2214: 	    } elsif ($token->[1] eq 'description' ||
 2215: 		     $token->[1] eq 'color'       ||
 2216: 		     $token->[1] eq 'show'          ) {
 2217: 		$key = $tag.'.'.$token->[1];
 2218: 	    } elsif ($token->[1] eq 'insert_sub') {
 2219: 		$key = $tag.'.function';
 2220: 	    } elsif ($token->[1] eq 'help') {
 2221: 		$in_help=1;
 2222: 	    } elsif ($token->[1] eq 'allow') {
 2223: 		$key = $tag.'.allow';
 2224: 	    }
 2225: 	    if (defined($key)) {
 2226: 		$insertlist{$key} = $parser->get_text();
 2227: 		$insertlist{$key} =~ s/(^\s*|\s*$ )//gx;
 2228: 	    }
 2229: 	} elsif ($token->[0] eq 'E') {
 2230: 	    if      ($token->[1] eq 'tag') {
 2231: 		undef($tag);
 2232: 		$tagnum++;
 2233: 	    } elsif ($token->[1] eq 'help') {
 2234: 		undef($in_help);
 2235: 	    }
 2236: 	}
 2237:     }
 2238:     
 2239:     # parse the allows and ignore tags set to <show>no</show>
 2240:     foreach my $tag (@alltags) {	
 2241:         next if (!exists($insertlist{$tag.'.allow'}));
 2242: 	my $allow =  $insertlist{$tag.'.allow'};
 2243:        	foreach my $element (split(',',$allow)) {
 2244: 	    $element =~ s/(^\s*|\s*$ )//gx;
 2245: 	    if (!exists($insertlist{$element.'.show'})
 2246:                 || $insertlist{$element.'.show'} ne 'no') {
 2247: 		push(@{ $insertlist{$tag.'.which'} },$element);
 2248: 	    }
 2249: 	}
 2250:     }
 2251: }
 2252: 
 2253: sub register_insert {
 2254:     return &register_insert_xml(@_);
 2255: #    &dump_insertlist('2');
 2256: }
 2257: 
 2258: sub dump_insertlist {
 2259:     my ($ext) = @_;
 2260:     open(XML,">/tmp/insertlist.xml.$ext");
 2261:     print XML ("<insertlist>");
 2262:     my $i=0;
 2263: 
 2264:     while (exists($insertlist{"$i.tag"})) {
 2265: 	my $tag = $insertlist{"$i.tag"};
 2266: 	print XML ("
 2267: \t<tag name=\"$tag\">");
 2268: 	if (defined($insertlist{"$tag.description"})) {
 2269: 	    print XML ("
 2270: \t\t<description>".$insertlist{"$tag.description"}."</description>");
 2271: 	}
 2272: 	if (defined($insertlist{"$tag.color"})) {
 2273: 	    print XML ("
 2274: \t\t<color>".$insertlist{"$tag.color"}."</color>");
 2275: 	}
 2276: 	if (defined($insertlist{"$tag.function"})) {
 2277: 	    print XML ("
 2278: \t\t<insert_sub>".$insertlist{"$tag.function"}."</insert_sub>");
 2279: 	}
 2280: 	if (defined($insertlist{"$tag.show"})
 2281: 	    && $insertlist{"$tag.show"} ne 'yes') {
 2282: 	    print XML ("
 2283: \t\t<show>".$insertlist{"$tag.show"}."</show>");
 2284: 	}
 2285: 	if (defined($insertlist{"$tag.helpfile"})) {
 2286: 	    print XML ("
 2287: \t\t<help>
 2288: \t\t\t<file>".$insertlist{"$tag.helpfile"}."</file>");
 2289: 	    if ($insertlist{"$tag.helpdesc"} ne '') {
 2290: 		print XML ("
 2291: \t\t\t<description>".$insertlist{"$tag.helpdesc"}."</description>");
 2292: 	    }
 2293: 	    print XML ("
 2294: \t\t</help>");
 2295: 	}
 2296: 	if (defined($insertlist{"$tag.which"})) {
 2297: 	    print XML ("
 2298: \t\t<allow>".join(',',sort(@{ $insertlist{"$tag.which"} }))."</allow>");
 2299: 	}
 2300: 	print XML ("
 2301: \t</tag>");
 2302: 	$i++;
 2303:     }
 2304:     print XML ("\n</insertlist>\n");
 2305:     close(XML);
 2306: }
 2307: 
 2308: sub description {
 2309:     my ($token)=@_;
 2310:     my $tag = &get_tag($token);
 2311:     return $insertlist{$tag.'.description'};
 2312: }
 2313: 
 2314: # Returns a list containing the help file, and the description
 2315: sub helpinfo {
 2316:     my ($token)=@_;
 2317:     my $tag = &get_tag($token);
 2318:     return ($insertlist{$tag.'.helpfile'}, &mt($insertlist{$tag.'.helpdesc'}));
 2319: }
 2320: 
 2321: sub get_tag {
 2322:     my ($token)=@_;
 2323:     my $tagnum;
 2324:     my $tag=$token->[1];
 2325:     foreach my $namespace (reverse(@Apache::lonxml::namespace)) {
 2326: 	my $testtag = $namespace.'::'.$tag;
 2327: 	$tagnum = $insertlist{"$testtag.num"};
 2328: 	last if (defined($tagnum));
 2329:     }
 2330:     if (!defined($tagnum)) {
 2331: 	$tagnum = $Apache::lonxml::insertlist{"$tag.num"};
 2332:     }
 2333:     return $insertlist{"$tagnum.tag"};
 2334: }
 2335: 
 2336: ############################################################
 2337: #                                           PDF-FORM-METHODS
 2338: 
 2339: =pod
 2340: 
 2341: =item &print_pdf_radiobutton(fieldname, value)
 2342: 
 2343: Returns a latexline to generate a PDF-Form-Radiobutton.
 2344: Note: Radiobuttons with equal names are automaticly grouped 
 2345:       in a selection-group.
 2346: 
 2347: $fieldname: PDF internalname of the radiobutton(group)
 2348: $value:     Value of radiobutton
 2349: 
 2350: =cut
 2351: sub print_pdf_radiobutton {
 2352:     my ($fieldname, $value) = @_;
 2353:     return '\radioButton[\symbolchoice{circle}]{'
 2354:            .$fieldname.'}{10bp}{10bp}{'.$value.'}';
 2355: }
 2356: 
 2357: 
 2358: =pod
 2359: 
 2360: =item &print_pdf_start_combobox(fieldname)
 2361: 
 2362: Starts a latexline to generate a PDF-Form-Combobox with text.
 2363: 
 2364: $fieldname: PDF internal name of the Combobox
 2365: 
 2366: =cut
 2367: sub print_pdf_start_combobox {
 2368:     my $result;
 2369:     my ($fieldName) = @_;
 2370:     $result .= '\begin{tabularx}{\textwidth}{p{2.5cm}X}'."\n";
 2371:     $result .= '\comboBox[]{'.$fieldName.'}{2.3cm}{14bp}{'; # 
 2372: 
 2373:     return $result;
 2374: }
 2375: 
 2376: 
 2377: =pod
 2378: 
 2379: =item &print_pdf_add_combobox_option(options)
 2380: 
 2381: Generates a latexline to add Options to a PDF-Form-ComboBox.
 2382: 
 2383: $option: PDF internal name of the Combobox-Option
 2384: 
 2385: =cut
 2386: sub print_pdf_add_combobox_option {
 2387: 
 2388:     my $result;
 2389:     my ($option) = @_;  
 2390: 
 2391:     $result .= '('.$option.')';
 2392:     
 2393:     return $result;
 2394: }
 2395: 
 2396: 
 2397: =pod
 2398: 
 2399: =item &print_pdf_end_combobox(text) {
 2400: 
 2401: Returns latexcode to end a PDF-Form-Combobox with text.
 2402: 
 2403: =cut
 2404: sub print_pdf_end_combobox {
 2405:     my $result;
 2406:     my ($text) = @_;
 2407: 
 2408:     $result .= '}&'.$text."\\\\\n";
 2409:     $result .= '\end{tabularx}' . "\n";
 2410:     $result .= '\hspace{2mm}' . "\n";
 2411:     return $result;
 2412: }
 2413: 
 2414: 
 2415: =pod
 2416: 
 2417: =item &print_pdf_hiddenField(fieldname, user, domain)
 2418: 
 2419: Returns a latexline to generate a PDF-Form-hiddenField with userdata.
 2420: 
 2421: $fieldname label for hiddentextfield
 2422: $user:    name of user
 2423: $domain:  domain of user
 2424: 
 2425: =cut
 2426: sub print_pdf_hiddenfield {
 2427:     my $result;
 2428:     my ($fieldname, $user, $domain) = @_;
 2429: 
 2430:     $result .= '\textField [\F{\FHidden}\F{-\FPrint}\V{'.$domain.'&'.$user.'}]{'.$fieldname.'}{0in}{0in}'."\n";
 2431: 
 2432:     return $result;
 2433: }
 2434: 
 2435: 1;
 2436: __END__
 2437: 

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