File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.505.2.7: download - view: text, annotated - select for diffs
Thu Dec 1 04:41:55 2011 UTC (12 years, 5 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_1, loncapaMITrelate_1
Diff to branchpoint 1.505: preferred, unified
- Backport 1.525.

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

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