File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.481: download - view: text, annotated - select for diffs
Wed Jun 25 12:00:37 2008 UTC (15 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_6_99_1, version_2_6_99_0, HEAD
Bug 5695.
Improved fix.  Earlier fix caused other things to break (e.g., scantron grading). Now explicitly pass a grade_noincrement form element in the ssi call to inhibit the unwanted second increment of the counter when displaying submission details ("by datess and submissions" case only).

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

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