File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.484.2.2: download - view: text, annotated - select for diffs
Fri Oct 24 19:36:40 2008 UTC (15 years, 7 months ago) by raeburn
Branches: version_2_7_X
Diff to branchpoint 1.484: preferred, unified
Backport 1.487.

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.484.2.2 2008/10/24 19:36:40 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(&mt('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(&mt('Using tag [_1] on line [_2] as end tag to [_3]','&lt;/'.$token->[1].'&gt;','.$token->[3].','&lt;'.$$stack[-1].'&gt;'));
  490: 		    last;
  491: 		} else {
  492:                     &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;'));
  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 ($token->[1] ne 'translated') {
  509: 	      if ( $#$parstack > -1 ) {
  510: 	          $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
  511: 	      } else {
  512: 	          $result=&Apache::run::evaluate($result,$safeeval,$extras);
  513: 	      }
  514:           }
  515:       }
  516:       $Apache::lonxml::post_evaluate=1;
  517: 
  518:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  519: 	  #Style file definitions should be correct
  520: 	  if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
  521: 	      $result=&latex_special_symbols($result);
  522: 	  }
  523:       }
  524: 
  525:       if ($Apache::lonxml::redirection) {
  526: 	$Apache::lonxml::outputstack['-1'] .= $result;
  527:       } else {
  528: 	$finaloutput.=$result;
  529:       }
  530:       $result = '';
  531: 
  532:       if ($token->[0] eq 'E' && !$dontpop) {
  533: 	&end_tag($stack,$parstack,$token);
  534:       }
  535:       $dontpop=0;
  536:     }	
  537:     if ($#$pars > -1) {
  538: 	pop @$pars;
  539: 	pop @Apache::lonxml::pwd;
  540:     }
  541:   }
  542: 
  543:   # if ($target eq 'meta') {
  544:   #   $finaloutput.=&endredirection;
  545:   # }
  546: 
  547:   if ( $start && $target eq 'grade') { &endredirection(); }
  548:   if ( $Apache::lonxml::redirection > $startredirection) {
  549:       while ($Apache::lonxml::redirection > $startredirection) {
  550: 	  $finaloutput .= &endredirection();
  551:       }
  552:   }
  553:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  554:     $finaloutput=&afterburn($finaloutput);
  555:   }	    
  556:   return $finaloutput;
  557: }
  558: 
  559: ## 
  560: ## Looks to see if there is a subroutine defined for this tag.  If so, call it,
  561: ## otherwise do not call it as we do not know what it is.
  562: ##
  563: sub callsub {
  564:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  565:   my $currentstring='';
  566:   my $nodefault;
  567:   {
  568:     my $sub1;
  569:     no strict 'refs';
  570:     my $tag=$token->[1];
  571: # get utterly rid of extended html tags
  572:     if ($tag=~/^x\-/i) { return ''; }
  573:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  574:     if (!$space) {
  575:      	$tag=~tr/A-Z/a-z/;
  576: 	$sub=~tr/A-Z/a-z/;
  577: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  578:     }
  579: 
  580:     my $deleted=0;
  581:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  582:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  583: 					     $parstack,$parser,$safeeval,
  584: 					     $style);
  585:     }
  586:     if (!$deleted) {
  587:       if ($space) {
  588: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
  589: 	$sub1="$space\:\:$sub";
  590: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  591: 					     $parstack,$parser,$safeeval,
  592: 					     $style);
  593:       } else {
  594:           if ($target eq 'tex') {
  595:               # throw away tag name
  596:               return '';
  597:           }
  598: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
  599: 	if ($metamode <1) {
  600: 	  if (defined($token->[4]) && ($metamode < 1)) {
  601: 	    $currentstring = $token->[4];
  602: 	  } else {
  603: 	    $currentstring = $token->[2];
  604: 	  }
  605: 	}
  606:       }
  607:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  608:       if ($currentstring eq '' && $nodefault eq '') {
  609: 	if ($target eq 'edit') {
  610: 	  #&Apache::lonxml::debug("doing default edit for $token->[1]");
  611: 	  if ($token->[0] eq 'S') {
  612: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  613: 	  } elsif ($token->[0] eq 'E') {
  614: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  615: 	  }
  616: 	}
  617:       }
  618:       if ($target eq 'modified' && $nodefault eq '') {
  619: 	  if ($currentstring eq '') {
  620: 	      if ($token->[0] eq 'S') {
  621: 		  $currentstring = $token->[4];
  622: 	      } elsif ($token->[0] eq 'E') {
  623: 		  $currentstring = $token->[2];
  624: 	      } else {
  625: 		  $currentstring = $token->[2];
  626: 	      }
  627: 	  }
  628: 	  if ($token->[0] eq 'S') {
  629: 	      $currentstring.=&Apache::edit::handle_insert();
  630: 	  } elsif ($token->[0] eq 'E') {
  631: 	      $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
  632: 	  }
  633:       }
  634:     }
  635:     use strict 'refs';
  636:   }
  637:   return $currentstring;
  638: }
  639: 
  640: {
  641:     my %state;
  642: 
  643:     sub init_state {
  644: 	undef(%state);
  645:     }
  646:     
  647:     sub set_state {
  648: 	my ($key,$value) = @_;
  649: 	$state{$key} = $value;
  650: 	return $value;
  651:     }
  652:     sub get_state {
  653: 	my ($key) = @_;
  654: 	return $state{$key};
  655:     }
  656: }
  657: 
  658: sub setup_globals {
  659:   my ($request,$target)=@_;
  660:   $Apache::lonxml::request=$request;
  661:   $errorcount=0;
  662:   $warningcount=0;
  663:   $Apache::lonxml::default_homework_loaded=0;
  664:   $Apache::lonxml::usestyle=1;
  665:   &init_counter();
  666:   &clear_bubble_lines_for_part();
  667:   &init_state();
  668:   &set_state('target',$target);
  669:   @Apache::lonxml::pwd=();
  670:   @Apache::lonxml::extlinks=();
  671:   @script_var_displays=();
  672:   @Apache::lonxml::ssi_info=();
  673:   $Apache::lonxml::post_evaluate=1;
  674:   $Apache::lonxml::warnings_error_header='';
  675:   $Apache::lonxml::substitute_LaTeX_symbols = 1;
  676:   if ($target eq 'meta') {
  677:     $Apache::lonxml::redirection = 0;
  678:     $Apache::lonxml::metamode = 1;
  679:     $Apache::lonxml::evaluate = 1;
  680:     $Apache::lonxml::import = 0;
  681:   } elsif ($target eq 'answer') {
  682:     $Apache::lonxml::redirection = 0;
  683:     $Apache::lonxml::metamode = 1;
  684:     $Apache::lonxml::evaluate = 1;
  685:     $Apache::lonxml::import = 1;
  686:   } elsif ($target eq 'grade') {
  687:     &startredirection(); #ended in inner_xmlparse on exit
  688:     $Apache::lonxml::metamode = 0;
  689:     $Apache::lonxml::evaluate = 1;
  690:     $Apache::lonxml::import = 1;
  691:   } elsif ($target eq 'modified') {
  692:     $Apache::lonxml::redirection = 0;
  693:     $Apache::lonxml::metamode = 0;
  694:     $Apache::lonxml::evaluate = 0;
  695:     $Apache::lonxml::import = 0;
  696:   } elsif ($target eq 'edit') {
  697:     $Apache::lonxml::redirection = 0;
  698:     $Apache::lonxml::metamode = 0;
  699:     $Apache::lonxml::evaluate = 0;
  700:     $Apache::lonxml::import = 0;
  701:   } elsif ($target eq 'analyze') {
  702:     $Apache::lonxml::redirection = 0;
  703:     $Apache::lonxml::metamode = 0;
  704:     $Apache::lonxml::evaluate = 1;
  705:     $Apache::lonxml::import = 1;
  706:   } else {
  707:     $Apache::lonxml::redirection = 0;
  708:     $Apache::lonxml::metamode = 0;
  709:     $Apache::lonxml::evaluate = 1;
  710:     $Apache::lonxml::import = 1;
  711:   }
  712: }
  713: 
  714: sub init_safespace {
  715:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  716:   $safeeval->deny_only(':dangerous');
  717:   $safeeval->reval('use Math::Complex;');
  718:   $safeeval->permit_only(":default");
  719:   $safeeval->permit("entereval");
  720:   $safeeval->permit(":base_math");
  721:   $safeeval->permit("sort");
  722:   $safeeval->permit("time");
  723:   $safeeval->permit("caller");
  724:   $safeeval->deny("rand");
  725:   $safeeval->deny("srand");
  726:   $safeeval->deny(":base_io");
  727:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  728:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
  729:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  730:   $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
  731: 		  '&chem_standard_order');
  732:   $safehole->wrap(\&Apache::response::check_status,$safeeval,'&check_status');
  733:   $safehole->wrap(\&Apache::response::implicit_multiplication,$safeeval,'&implicit_multiplication');
  734: 
  735:   $safehole->wrap(\&Apache::lonmaxima::maxima_eval,$safeeval,'&maxima_eval');
  736:   $safehole->wrap(\&Apache::lonmaxima::maxima_check,$safeeval,'&maxima_check');
  737:   $safehole->wrap(\&Apache::lonmaxima::maxima_cas_formula_fix,$safeeval,
  738: 		  '&maxima_cas_formula_fix');
  739: 
  740:   $safehole->wrap(\&Apache::caparesponse::capa_formula_fix,$safeeval,
  741: 		  '&capa_formula_fix');
  742: 
  743:   $safehole->wrap(\&Apache::lonlocal::locallocaltime,$safeeval,
  744:                   '&locallocaltime');
  745: 
  746:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  747:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  748:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  749:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  750:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  751:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  752:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  753:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  754:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  755:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  756:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  757:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  758:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  759:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  760:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  761:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  762:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  763:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  764:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  765:   
  766:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
  767:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
  768:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
  769:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
  770:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
  771:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
  772:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
  773:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
  774:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
  775:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
  776:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
  777:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
  778:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
  779:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
  780:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
  781:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
  782:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
  783:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
  784:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
  785:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
  786:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
  787:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
  788: 
  789:   $safehole->wrap(\&Math::Cephes::Matrix::mat,$safeeval,'&mat');
  790:   $safehole->wrap(\&Math::Cephes::Matrix::new,$safeeval,
  791: 		  '&Math::Cephes::Matrix::new');
  792:   $safehole->wrap(\&Math::Cephes::Matrix::coef,$safeeval,
  793: 		  '&Math::Cephes::Matrix::coef');
  794:   $safehole->wrap(\&Math::Cephes::Matrix::clr,$safeeval,
  795: 		  '&Math::Cephes::Matrix::clr');
  796:   $safehole->wrap(\&Math::Cephes::Matrix::add,$safeeval,
  797: 		  '&Math::Cephes::Matrix::add');
  798:   $safehole->wrap(\&Math::Cephes::Matrix::sub,$safeeval,
  799: 		  '&Math::Cephes::Matrix::sub');
  800:   $safehole->wrap(\&Math::Cephes::Matrix::mul,$safeeval,
  801: 		  '&Math::Cephes::Matrix::mul');
  802:   $safehole->wrap(\&Math::Cephes::Matrix::div,$safeeval,
  803: 		  '&Math::Cephes::Matrix::div');
  804:   $safehole->wrap(\&Math::Cephes::Matrix::inv,$safeeval,
  805: 		  '&Math::Cephes::Matrix::inv');
  806:   $safehole->wrap(\&Math::Cephes::Matrix::transp,$safeeval,
  807: 		  '&Math::Cephes::Matrix::transp');
  808:   $safehole->wrap(\&Math::Cephes::Matrix::simq,$safeeval,
  809: 		  '&Math::Cephes::Matrix::simq');
  810:   $safehole->wrap(\&Math::Cephes::Matrix::mat_to_vec,$safeeval,
  811: 		  '&Math::Cephes::Matrix::mat_to_vec');
  812:   $safehole->wrap(\&Math::Cephes::Matrix::vec_to_mat,$safeeval,
  813: 		  '&Math::Cephes::Matrix::vec_to_mat');
  814:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
  815: 		  '&Math::Cephes::Matrix::check');
  816:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
  817: 		  '&Math::Cephes::Matrix::check');
  818: 
  819: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
  820: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
  821: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
  822: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
  823: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
  824: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
  825: 
  826:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  827:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  828:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  829:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  830:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  831:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  832:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  833:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  834:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  835:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  836:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  837:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  838:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  839:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  840:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  841:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  842:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  843:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  844:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  845:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  846:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  847:   $safehole->wrap(\&Apache::loncommon::languages,$safeeval,'&languages');
  848:   $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
  849:   $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
  850:   $safehole->wrap(\&Apache::lonnet::logthis,$safeeval,'&LONCAPA_INTERNAL_LOGTHIS');
  851:   $safehole->wrap(\&Apache::inputtags::finalizeawards,$safeeval,'&LONCAPA_INTERNAL_FINALIZEAWARDS');
  852:   $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
  853: #  use Data::Dumper;
  854: #  $safehole->wrap(\&Data::Dumper::Dumper,$safeeval,'&LONCAPA_INTERNAL_Dumper');
  855: #need to inspect this class of ops
  856: # $safeeval->deny(":base_orig");
  857:   $safeeval->permit("require");
  858:   $safeinit .= ';$external::target="'.$target.'";';
  859:   &Apache::run::run($safeinit,$safeeval);
  860:   &initialize_rndseed($safeeval);
  861: }
  862: 
  863: sub clean_safespace {
  864:     my ($safeeval) = @_;
  865:     delete_package_recurse($safeeval->{Root});
  866: }
  867: 
  868: sub delete_package_recurse {
  869:      my ($package) = @_;
  870:      my @subp;
  871:      {
  872: 	 no strict 'refs';
  873: 	 while (my ($key,$val) = each(%{*{"$package\::"}})) {
  874: 	     if (!defined($val)) { next; }
  875: 	     local (*ENTRY) = $val;
  876: 	     if (defined *ENTRY{HASH} && $key =~ /::$/ &&
  877: 		 $key ne "main::" && $key ne "<none>::")
  878: 	     {
  879: 		 my ($p) = $package ne "main" ? "$package\::" : "";
  880: 		 ($p .= $key) =~ s/::$//;
  881: 		 push(@subp,$p);
  882: 	     }
  883: 	 }
  884:      }
  885:      foreach my $p (@subp) {
  886: 	 delete_package_recurse($p);
  887:      }
  888:      Symbol::delete_package($package);
  889: }
  890: 
  891: sub initialize_rndseed {
  892:     my ($safeeval)=@_;
  893:     my $rndseed;
  894:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
  895:     $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  896:     my $safeinit = '$external::randomseed="'.$rndseed.'";';
  897:     &Apache::lonxml::debug("Setting rndseed to $rndseed");
  898:     &Apache::run::run($safeinit,$safeeval);
  899: }
  900: 
  901: sub default_homework_load {
  902:     my ($safeeval)=@_;
  903:     &Apache::lonxml::debug('Loading default_homework');
  904:     my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
  905:     if ($default eq -1) {
  906: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
  907:     } else {
  908: 	&Apache::run::run($default,$safeeval);
  909: 	$Apache::lonxml::default_homework_loaded=1;
  910:     }
  911: }
  912: 
  913: {
  914:     my $alarm_depth;
  915:     sub init_alarm {
  916: 	alarm(0);
  917: 	$alarm_depth=0;
  918:     }
  919: 
  920:     sub start_alarm {
  921: 	if ($alarm_depth<1) {
  922: 	    my $old=alarm($Apache::lonnet::perlvar{'lonScriptTimeout'});
  923: 	    if ($old) {
  924: 		&Apache::lonxml::error("Cancelled an alarm of $old, this shouldn't occur.");
  925: 	    }
  926: 	}
  927: 	$alarm_depth++;
  928:     }
  929: 
  930:     sub end_alarm {
  931: 	$alarm_depth--;
  932: 	if ($alarm_depth<1) { alarm(0); }
  933:     }
  934: }
  935: my $metamode_was;
  936: sub startredirection {
  937:     if (!$Apache::lonxml::redirection) {
  938: 	$metamode_was=$Apache::lonxml::metamode;
  939:     }
  940:     $Apache::lonxml::metamode=0;
  941:     $Apache::lonxml::redirection++;
  942:     push (@Apache::lonxml::outputstack, '');
  943: }
  944: 
  945: sub endredirection {
  946:     if (!$Apache::lonxml::redirection) {
  947: 	&Apache::lonxml::error("Endredirection was called before a startredirection, perhaps you have unbalanced tags. Some debugging information:".join ":",caller);
  948: 	return '';
  949:     }
  950:     $Apache::lonxml::redirection--;
  951:     if (!$Apache::lonxml::redirection) {
  952: 	$Apache::lonxml::metamode=$metamode_was;
  953:     }
  954:     pop @Apache::lonxml::outputstack;
  955: }
  956: sub in_redirection {
  957:     return ($Apache::lonxml::redirection > 0)
  958: }
  959: 
  960: sub end_tag {
  961:   my ($tagstack,$parstack,$token)=@_;
  962:   pop(@$tagstack);
  963:   pop(@$parstack);
  964:   &decreasedepth($token);
  965: }
  966: 
  967: sub initdepth {
  968:   @Apache::lonxml::depthcounter=();
  969:   undef($Apache::lonxml::last_depth_count);
  970: }
  971: 
  972: 
  973: my @timers;
  974: my $lasttime;
  975: # @Apache::lonxml::depthcounter -> count of tags that exist so
  976: #                                  far at each level
  977: # $Apache::lonxml::last_depth_count -> when ascending, need to
  978: # remember the count for the level below the current level (for
  979: # example going from 1_2 -> 1 -> 1_3 need to remember the 2 )
  980: 
  981: sub increasedepth {
  982:   my ($token) = @_;
  983:   push(@Apache::lonxml::depthcounter,$Apache::lonxml::last_depth_count+1);
  984:   undef($Apache::lonxml::last_depth_count);
  985:   my $time;
  986:   if ($Apache::lonxml::debug eq "1") {
  987:       push(@timers,[&gettimeofday()]);
  988:       $time=&tv_interval($lasttime);
  989:       $lasttime=[&gettimeofday()];
  990:   }
  991:   my $spacing='  'x($#Apache::lonxml::depthcounter);
  992:   $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
  993: #  &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time");
  994: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  995: }
  996: 
  997: sub decreasedepth {
  998:   my ($token) = @_;
  999:   if (  $#Apache::lonxml::depthcounter == -1) {
 1000:       &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
 1001:   }
 1002:   $Apache::lonxml::last_depth_count = pop(@Apache::lonxml::depthcounter);
 1003: 
 1004:   my ($timer,$time);
 1005:   if ($Apache::lonxml::debug eq "1") {
 1006:       $timer=pop(@timers);
 1007:       $time=&tv_interval($lasttime);
 1008:       $lasttime=[&gettimeofday()];
 1009:   }
 1010:   my $spacing='  'x($#Apache::lonxml::depthcounter);
 1011:   $Apache::lonxml::curdepth = join('_',@Apache::lonxml::depthcounter);
 1012: #  &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time : ".&tv_interval($timer));
 1013: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
 1014: }
 1015: 
 1016: sub get_id {
 1017:     my ($parstack,$safeeval)=@_;
 1018:     my $id= &Apache::lonxml::get_param('id',$parstack,$safeeval);
 1019:     if ($env{'request.state'} eq 'construct' && $id =~ /([._]|[^\w\d\s[:punct:]])/) {
 1020: 	&error(&mt("ID &quot;[_1]&quot; contains invalid characters, IDs are only allowed to contain letters, numbers, spaces and -",'<tt>'.$id.'</tt>'));
 1021:     }
 1022:     if ($id =~ /^\s*$/) { $id = $Apache::lonxml::curdepth; }
 1023:     return $id;
 1024: }
 1025: 
 1026: sub get_all_text_unbalanced {
 1027: #there is a copy of this in lonpublisher.pm
 1028:     my($tag,$pars)= @_;
 1029:     my $token;
 1030:     my $result='';
 1031:     $tag='<'.$tag.'>';
 1032:     while ($token = $$pars[-1]->get_token) {
 1033: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
 1034: 	    if ($token->[0] eq 'T' && $token->[2]) {
 1035: 		$result.='<![CDATA['.$token->[1].']]>';
 1036: 	    } else {
 1037: 		$result.=$token->[1];
 1038: 	    }
 1039: 	} elsif ($token->[0] eq 'PI') {
 1040: 	    $result.=$token->[2];
 1041: 	} elsif ($token->[0] eq 'S') {
 1042: 	    $result.=$token->[4];
 1043: 	} elsif ($token->[0] eq 'E')  {
 1044: 	    $result.=$token->[2];
 1045: 	}
 1046: 	if ($result =~ /\Q$tag\E/is) {
 1047: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
 1048: 	    #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
 1049: 	    #&Apache::lonxml::debug('Result is :'.$1);
 1050: 	    $redo=$tag.$redo;
 1051: 	    &Apache::lonxml::newparser($pars,\$redo);
 1052: 	    last;
 1053: 	}
 1054:     }
 1055:     return $result
 1056: 
 1057: }
 1058: 
 1059: #########################################################################
 1060: #                                                                       #
 1061: #           bubble line counter management                              #
 1062: #                                                                       #
 1063: #########################################################################
 1064: 
 1065: =pod
 1066: 
 1067: For bubble grading mode and exam bubble printing mode, the tracking of
 1068: the current 'bubble line number' is stored in the %env element
 1069: 'form.counter', and is modifed and handled by the following routines.
 1070: 
 1071: The value of it is stored in $Apache:lonxml::counter when live and
 1072: stored back to env after done.
 1073: 
 1074: =item &increment_counter($increment);
 1075: 
 1076: Increments the internal counter environment variable a specified amount
 1077: 
 1078: Optional Arguments:
 1079:   $increment - amount to increment by (defaults to 1)
 1080:                Also 1 if the value is negative or zero.
 1081:   $part_response - A concatenation of the part and response id
 1082:                    identifying exactly what is being 'answered'.
 1083: 
 1084: 
 1085: =cut
 1086: 
 1087: sub increment_counter {
 1088:     my ($increment, $part_response) = @_;
 1089:     if ($env{'form.grade_noincrement'}) { return; }
 1090:     if (!defined($increment) || $increment le 0) {
 1091: 	$increment = 1;
 1092:     }
 1093:     $Apache::lonxml::counter += $increment;
 1094: 
 1095:     # If the caller supplied the response_id parameter, 
 1096:     # Maintain its counter.. creating if necessary.
 1097: 
 1098:     if (defined($part_response)) {
 1099: 	if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
 1100: 	    $Apache::lonxml::counters_per_part{$part_response} = 0;
 1101: 	}
 1102: 	$Apache::lonxml::counters_per_part{$part_response} += $increment;
 1103: 	my $new_value = $Apache::lonxml::counters_per_part{$part_response};
 1104:     }
 1105: 	
 1106:     $Apache::lonxml::counter_changed=1;
 1107: }
 1108: 
 1109: =pod
 1110: 
 1111: =item &init_counter($increment);
 1112: 
 1113: Initialize the internal counter environment variable
 1114: 
 1115: =cut
 1116: 
 1117: sub init_counter {
 1118:     if ($env{'request.state'} eq 'construct') {
 1119: 	$Apache::lonxml::counter=1;
 1120: 	$Apache::lonxml::counter_changed=1;
 1121:     } elsif (defined($env{'form.counter'})) {
 1122: 	$Apache::lonxml::counter=$env{'form.counter'};
 1123: 	$Apache::lonxml::counter_changed=0;
 1124:     } else {
 1125: 	$Apache::lonxml::counter=1;
 1126: 	$Apache::lonxml::counter_changed=1;
 1127:     }
 1128: }
 1129: 
 1130: sub store_counter {
 1131:     &Apache::lonnet::appenv({'form.counter' => $Apache::lonxml::counter});
 1132:     $Apache::lonxml::counter_changed=0;
 1133:     return '';
 1134: }
 1135: 
 1136: {
 1137:     my $state;
 1138:     sub clear_problem_counter {
 1139: 	undef($state);
 1140: 	&Apache::lonnet::delenv('form.counter');
 1141: 	&Apache::lonxml::init_counter();
 1142: 	&Apache::lonxml::store_counter();
 1143:     }
 1144: 
 1145:     sub remember_problem_counter {
 1146: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
 1147: 	$state = $env{'form.counter'};
 1148:     }
 1149: 
 1150:     sub restore_problem_counter {
 1151: 	if (defined($state)) {
 1152: 	    &Apache::lonnet::appenv({'form.counter' => $state});
 1153: 	}
 1154:     }
 1155:     sub get_problem_counter {
 1156: 	if ($Apache::lonxml::counter_changed) { &store_counter() }
 1157: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
 1158: 	return $env{'form.counter'};
 1159:     }
 1160: }
 1161: 
 1162: =pod
 1163: 
 1164: =item  bubble_lines_for_part(part_response)
 1165: 
 1166: Returns the number of lines required to get a response for
 1167: $part_response (this is just $Apache::lonxml::counters_per_part{$part_response}
 1168: 
 1169: =cut
 1170: 
 1171: sub bubble_lines_for_part {
 1172:     my ($part_response) = @_;
 1173: 
 1174:     if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
 1175: 	return 0;
 1176:     } else {
 1177: 	return $Apache::lonxml::counters_per_part{$part_response};
 1178:     }
 1179: }
 1180: 
 1181: =pod
 1182: 
 1183: =item clear_bubble_lines_for_part
 1184: 
 1185: Clears the hash of bubble lines per part.  If a caller
 1186: needs to analyze several resources this should be called between
 1187: resources to reset the hash for each problem being analyzed.
 1188: 
 1189: =cut
 1190: 
 1191: sub clear_bubble_lines_for_part {
 1192:     undef(%Apache::lonxml::counters_per_part);
 1193: }
 1194: 
 1195: =pod
 1196: 
 1197: =item set_bubble_lines(part_response, value)
 1198: 
 1199: If there is a problem part, that for whatever reason
 1200: requires bubble lines that are not
 1201: the same as the counter increment, it can call this sub during
 1202: analysis to set its hash value explicitly.
 1203: 
 1204: =cut
 1205: 
 1206: sub set_bubble_lines {
 1207:     my ($part_response, $value) = @_;
 1208: 
 1209:     $Apache::lonxml::counters_per_part{$part_response} = $value;
 1210: }
 1211: 
 1212: =pod
 1213: 
 1214: =item get_bubble_line_hash
 1215: 
 1216: Returns the current bubble line hash.  This is assumed to 
 1217: be small so we return a copy
 1218: 
 1219: 
 1220: =cut
 1221: 
 1222: sub get_bubble_line_hash {
 1223:     return %Apache::lonxml::counters_per_part;
 1224: }
 1225: 
 1226: 
 1227: #--------------------------------------------------
 1228: 
 1229: sub get_all_text {
 1230:     my($tag,$pars,$style)= @_;
 1231:     my $gotfullstack=1;
 1232:     if (ref($pars) ne 'ARRAY') {
 1233: 	$gotfullstack=0;
 1234: 	$pars=[$pars];
 1235:     }
 1236:     if (ref($style) ne 'HASH') {
 1237: 	$style={};
 1238:     }
 1239:     my $depth=0;
 1240:     my $token;
 1241:     my $result='';
 1242:     if ( $tag =~ m:^/: ) { 
 1243: 	my $tag=substr($tag,1); 
 1244: 	#&Apache::lonxml::debug("have:$tag:");
 1245: 	my $top_empty=0;
 1246: 	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
 1247: 	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
 1248: 		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
 1249: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
 1250: 		    if ($token->[2]) {
 1251: 			$result.='<![CDATA['.$token->[1].']]>';
 1252: 		    } else {
 1253: 			$result.=$token->[1];
 1254: 		    }
 1255: 		} elsif ($token->[0] eq 'PI') {
 1256: 		    $result.=$token->[2];
 1257: 		} elsif ($token->[0] eq 'S') {
 1258: 		    if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
 1259: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1260: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1261: 		    $result.=$token->[4];
 1262: 		} elsif ($token->[0] eq 'E')  {
 1263: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
 1264: 		    #skip sending back the last end tag
 1265: 		    if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
 1266: 			my $string=
 1267: 			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
 1268: 				$$style{'/'.$token->[1]}.
 1269: 				    $token->[2].
 1270: 					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
 1271: 			&Apache::lonxml::newparser($pars,\$string);
 1272: 			#&Apache::lonxml::debug("reParsing $string");
 1273: 			next;
 1274: 		    }
 1275: 		    if ($depth > -1) {
 1276: 			$result.=$token->[2];
 1277: 		    } else {
 1278: 			$$pars[-1]->unget_token($token);
 1279: 		    }
 1280: 		}
 1281: 	    }
 1282: 	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
 1283: 	    if (($depth >=0) && ($#$pars > 0) ) {
 1284: 		pop(@$pars);
 1285: 		pop(@Apache::lonxml::pwd);
 1286: 	    }
 1287: 	}
 1288: 	if ($top_empty && $depth >= 0) {
 1289: 	    #never found the end tag ran out of text, throw error send back blank
 1290: 	    &error('Never found end tag for &lt;'.$tag.
 1291: 		   '&gt; current string <pre>'.
 1292: 		   &HTML::Entities::encode($result,'<>&"').
 1293: 		   '</pre>');
 1294: 	    if ($gotfullstack) {
 1295: 		my $newstring='</'.$tag.'>'.$result;
 1296: 		&Apache::lonxml::newparser($pars,\$newstring);
 1297: 	    }
 1298: 	    $result='';
 1299: 	}
 1300:     } else {
 1301: 	while ($#$pars > -1) {
 1302: 	    while ($token = $$pars[-1]->get_token) {
 1303: 		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
 1304: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
 1305: 		    ($token->[0] eq 'D')) {
 1306: 		    if ($token->[2]) {
 1307: 			$result.='<![CDATA['.$token->[1].']]>';
 1308: 		    } else {
 1309: 			$result.=$token->[1];
 1310: 		    }
 1311: 		} elsif ($token->[0] eq 'PI') {
 1312: 		    $result.=$token->[2];
 1313: 		} elsif ($token->[0] eq 'S') {
 1314: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) {
 1315: 			$$pars[-1]->unget_token($token); last;
 1316: 		    } else {
 1317: 			$result.=$token->[4];
 1318: 		    }
 1319: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1320: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1321: 		} elsif ($token->[0] eq 'E')  {
 1322: 		    $result.=$token->[2];
 1323: 		}
 1324: 	    }
 1325: 	    if (($#$pars > 0) ) {
 1326: 		pop(@$pars);
 1327: 		pop(@Apache::lonxml::pwd);
 1328: 	    } else { last; }
 1329: 	}
 1330:     }
 1331:     #&Apache::lonxml::debug("Exit:$result:");
 1332:     return $result
 1333: }
 1334: 
 1335: sub newparser {
 1336:   my ($parser,$contentref,$dir) = @_;
 1337:   push (@$parser,HTML::LCParser->new($contentref));
 1338:   $$parser[-1]->xml_mode(1);
 1339:   $$parser[-1]->marked_sections(1);
 1340:   if ( $dir eq '' ) {
 1341:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
 1342:   } else {
 1343:     push (@Apache::lonxml::pwd, $dir);
 1344:   } 
 1345: }
 1346: 
 1347: sub parstring {
 1348:     my ($token) = @_;
 1349:     my (@vars,@values);
 1350:     foreach my $attr (@{$token->[3]}) {
 1351: 	if ($attr!~/\W/) {
 1352: 	    my $val=$token->[2]->{$attr};
 1353: 	    $val =~ s/([\%\@\\\"\'])/\\$1/g;
 1354: 	    $val =~ s/(\$[^\{a-zA-Z_])/\\$1/g;
 1355: 	    $val =~ s/(\$)$/\\$1/;
 1356: 	    #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
 1357: 	    push(@vars,"\$$attr");
 1358: 	    push(@values,"\"$val\"");
 1359: 	}
 1360:     }
 1361:     my $var_init = 
 1362: 	(@vars) ? 'my ('.join(',',@vars).') = ('.join(',',@values).');'
 1363: 	        : '';
 1364:     return $var_init;
 1365: }
 1366: 
 1367: sub extlink {
 1368:     my ($res,$exact)=@_;
 1369:     if (!$exact) {
 1370: 	$res=&Apache::lonnet::hreflocation($Apache::lonxml::pwd[-1],$res);
 1371:     }
 1372:     push(@Apache::lonxml::extlinks,$res)	 
 1373: }
 1374: 
 1375: sub writeallows {
 1376:     unless ($#extlinks>=0) { return; }
 1377:     my $thisurl = &Apache::lonnet::clutter(shift);
 1378:     if ($env{'httpref.'.$thisurl}) {
 1379: 	$thisurl=$env{'httpref.'.$thisurl};
 1380:     }
 1381:     my $thisdir=$thisurl;
 1382:     $thisdir=~s/\/[^\/]+$//;
 1383:     my %httpref=();
 1384:     foreach (@extlinks) {
 1385:        $httpref{'httpref.'.
 1386:  	        &Apache::lonnet::hreflocation($thisdir,&unescape($_))}=$thisurl;
 1387:     }
 1388:     @extlinks=();
 1389:     &Apache::lonnet::appenv(\%httpref);
 1390: }
 1391: 
 1392: sub register_ssi {
 1393:     my ($url,%form)=@_;
 1394:     push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
 1395:     return '';
 1396: }
 1397: 
 1398: sub do_registered_ssi {
 1399:     foreach my $info (@Apache::lonxml::ssi_info) {
 1400: 	my %form=%{ $info->{'form'}};
 1401: 	my $url=$info->{'url'};
 1402: 	&Apache::lonnet::ssi($url,%form);
 1403:     }
 1404: }
 1405: 
 1406: sub add_script_result {
 1407:     my ($display) = @_;
 1408:     push(@script_var_displays, $display);
 1409: }
 1410: 
 1411: #
 1412: # Afterburner handles anchors, highlights and links
 1413: #
 1414: sub afterburn {
 1415:     my $result=shift;
 1416:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1417: 					    ['highlight','anchor','link']);
 1418:     if ($env{'form.highlight'}) {
 1419:        foreach (split(/\,/,$env{'form.highlight'})) {
 1420:            my $anchorname=$_;
 1421: 	   my $matchthis=$anchorname;
 1422:            $matchthis=~s/\_+/\\s\+/g;
 1423:            $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1424:        }
 1425:     }
 1426:     if ($env{'form.link'}) {
 1427:        foreach (split(/\,/,$env{'form.link'})) {
 1428:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1429: 	   my $matchthis=$anchorname;
 1430:            $matchthis=~s/\_+/\\s\+/g;
 1431:            $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1432:        }
 1433:     }
 1434:     if ($env{'form.anchor'}) {
 1435:         my $anchorname=$env{'form.anchor'};
 1436: 	my $matchthis=$anchorname;
 1437:         $matchthis=~s/\_+/\\s\+/g;
 1438:         $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1439:         $result.=(<<"ENDSCRIPT");
 1440: <script type="text/javascript">
 1441:     document.location.hash='$anchorname';
 1442: </script>
 1443: ENDSCRIPT
 1444:     }
 1445:     return $result;
 1446: }
 1447: 
 1448: sub storefile {
 1449:     my ($file,$contents)=@_;
 1450:     &Apache::lonnet::correct_line_ends(\$contents);
 1451:     if (my $fh=Apache::File->new('>'.$file)) {
 1452: 	print $fh $contents;
 1453:         $fh->close();
 1454:         return 1;
 1455:     } else {
 1456: 	&warning(&mt('Unable to save file [_1]','<tt>'.$file.'</tt>'));
 1457: 	return 0;
 1458:     }
 1459: }
 1460: 
 1461: sub createnewhtml {
 1462:     my $title=&mt('Title of document goes here');
 1463:     my $body=&mt('Body of document goes here');
 1464:     my $filecontents=(<<SIMPLECONTENT);
 1465: <html>
 1466: <head>
 1467: <title>$title</title>
 1468: </head>
 1469: <body bgcolor="#FFFFFF">
 1470: $body
 1471: </body>
 1472: </html>
 1473: SIMPLECONTENT
 1474:     return $filecontents;
 1475: }
 1476: 
 1477: sub createnewsty {
 1478:   my $filecontents=(<<SIMPLECONTENT);
 1479: <definetag name="">
 1480:     <render>
 1481:        <web></web>
 1482:        <tex></tex>
 1483:     </render>
 1484: </definetag>
 1485: SIMPLECONTENT
 1486:   return $filecontents;
 1487: }
 1488: 
 1489: sub verify_html {
 1490:     my ($filecontents)=@_;
 1491:     if ($filecontents!~/(?:\<|\&lt\;)(?:html|xml)[^\<]*(?:\>|\&gt\;)/is) {
 1492:        return &mt('File does not have [_1] or [_2] starting tag','&lt;html&gt;','&lt;xml&gt;');
 1493:     }
 1494:     if ($filecontents!~/(?:\<|\&lt\;)\/(?:html|xml)(?:\>|\&gt\;)/is) {
 1495:        return &mt('File does not have [_1] or [_2] ending tag','&lt;html&gt;','&lt;xml&gt;');
 1496:     }
 1497:     if ($filecontents!~/(?:\<|\&lt\;)(?:body|frameset)[^\<]*(?:\>|\&gt\;)/is) {
 1498:        return &mt('File does not have [_1] or [_2] starting tag','&lt;body&gt;','&lt;frameset&gt;');
 1499:     }
 1500:     if ($filecontents!~/(?:\<|\&lt\;)\/(?:body|frameset)[^\<]*(?:\>|\&gt\;)/is) {
 1501:        return &mt('File does not have [_1] or [_2] ending tag','&lt;body&gt;','&lt;frameset&gt;');
 1502:     }
 1503:     return '';
 1504: }
 1505: 
 1506: sub renderingoptions {
 1507:     my %langchoices=('' => '');
 1508:     foreach (&Apache::loncommon::languageids()) {
 1509:         if (&Apache::loncommon::supportedlanguagecode($_)) {
 1510:             $langchoices{&Apache::loncommon::supportedlanguagecode($_)}
 1511:                        = &Apache::loncommon::plainlanguagedescription($_);
 1512:         }
 1513:     }
 1514:     return
 1515:        '<span class="LC_nobreak">'.
 1516:        &mt('Language:').' '.
 1517:        &Apache::loncommon::select_form($env{'form.languages'},'languages',
 1518:                                                      %langchoices).'
 1519:      </span>
 1520:      <span class="LC_nobreak">'.
 1521:        &mt('Math Rendering:').' '.
 1522:        &Apache::loncommon::select_form($env{'form.texengine'},'texengine',
 1523:                                                      ('' => '',
 1524:                                                       'tth' => 'tth (TeX to HTML)',
 1525:                                                       'jsMath' => 'jsMath',
 1526:                                                       'mimetex' => 'mimetex (Convert to Images)')).'
 1527:      </span>';
 1528: }
 1529: 
 1530: sub inserteditinfo {
 1531:       my ($filecontents, $filetype, $filename)=@_;
 1532:       $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
 1533:       my $xml_help = '';
 1534:       my $initialize='';
 1535:       my $textarea_id = 'filecont';
 1536:       my ($add_to_onload, $add_to_onresize);
 1537:       $initialize=&Apache::lonhtmlcommon::spellheader();
 1538:       if ($filetype eq 'html' 
 1539: 	  && (!&Apache::lonhtmlcommon::htmlareablocked() &&
 1540: 	      &Apache::lonhtmlcommon::htmlareabrowser())) {
 1541: 	  $textarea_id .= '___Frame';
 1542: 	  my $lang = &Apache::lonhtmlcommon::htmlarea_lang();
 1543: 	  $initialize.=(<<FULLPAGE);
 1544: <script type="text/javascript">
 1545: lonca
 1546:     function initDocument() {
 1547:         var oFCKeditor = new FCKeditor('filecont');
 1548: 	oFCKeditor.Config['CustomConfigurationsPath'] = '/fckeditor/loncapaconfig.js'  ;
 1549: 	oFCKeditor.Config['FullPage'] = true
 1550: 	oFCKeditor.Config['AutoDetectLanguage'] = false;
 1551:         oFCKeditor.Config['DefaultLanguage'] = "$lang";
 1552: 	oFCKeditor.ReplaceTextarea();
 1553:     }
 1554:     function check_if_dirty(editor) {
 1555: 	if (editor.IsDirty()) {
 1556: 	    unClean();
 1557: 	}
 1558:     }
 1559:     function FCKeditor_OnComplete(editor) {
 1560: 	editor.Events.AttachEvent("OnSelectionChange",check_if_dirty);
 1561: 	resize_textarea('$textarea_id','LC_aftertextarea');
 1562:     }
 1563: </script>
 1564: FULLPAGE
 1565:       } else {
 1566: 	  $initialize.=(<<FULLPAGE);
 1567: <script type="text/javascript">
 1568:     function initDocument() {
 1569: 	resize_textarea('$textarea_id','LC_aftertextarea');
 1570:     }
 1571: </script>
 1572: FULLPAGE
 1573:       }
 1574: 
 1575:       $add_to_onload = 'initDocument();';
 1576:       $add_to_onresize = "resize_textarea('$textarea_id','LC_aftertextarea');";
 1577: 
 1578:       if ($filetype eq 'html') {
 1579: 	  $xml_help=&Apache::loncommon::helpLatexCheatsheet();
 1580:       }
 1581: 
 1582:       my $titledisplay=&display_title();
 1583:       my %lt=&Apache::lonlocal::texthash('st' => 'Save and Edit',
 1584: 					 'vi' => 'Save and View',
 1585: 					 'dv' => 'Discard Edits and View',
 1586: 					 'un' => 'undo',
 1587: 					 'ed' => 'Edit');
 1588:       my $spelllink .=&Apache::lonhtmlcommon::spelllink('xmledit','filecont');
 1589:       my $textarea_events = &Apache::edit::element_change_detection();
 1590:       my $form_events     = &Apache::edit::form_change_detection();
 1591:       my $htmlerror=&verify_html($filecontents);
 1592:       if ($htmlerror) {
 1593:          $htmlerror='<span class="LC_error">'.$htmlerror.'</span>';
 1594:       }
 1595:       my $editfooter=(<<ENDFOOTER);
 1596: $initialize
 1597: <a name="editsection" />
 1598: <form $form_events method="post" name="xmledit">
 1599:   <div class="LC_edit_problem_editxml_header">
 1600:     <table class="LC_edit_problem_header_title"><tr><td>
 1601:         $filename
 1602:       </td><td align="right">
 1603:         $xml_help
 1604:       </td></tr>
 1605:     </table>
 1606:     <div class="LC_edit_problem_discards">
 1607:       <input type="submit" name="discardview" accesskey="d" value="$lt{'dv'}" />
 1608:       <input type="submit" name="Undo" accesskey="u" value="$lt{'un'}" />
 1609:       $spelllink $htmlerror
 1610:     </div>
 1611:     <div class="LC_edit_problem_saves">
 1612:       <input type="submit" name="savethisfile" accesskey="s" value="$lt{'st'}" />
 1613:       <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
 1614:     </div>
 1615:   </div>
 1616:   <textarea $textarea_events style="width:100%" cols="80" rows="44" name="filecont" id="filecont">$filecontents</textarea>
 1617:   <div id="LC_aftertextarea">
 1618:     <br />
 1619:     $titledisplay
 1620:   </div>
 1621: </form>
 1622: </body>
 1623: ENDFOOTER
 1624:       return ($editfooter,$add_to_onload,$add_to_onresize);;
 1625: }
 1626: 
 1627: sub get_target {
 1628:   my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
 1629:   if ( $env{'request.state'} eq 'published') {
 1630:     if ( defined($env{'form.grade_target'})
 1631: 	 && ($viewgrades == 'F' )) {
 1632:       return ($env{'form.grade_target'});
 1633:     } elsif (defined($env{'form.grade_target'})) {
 1634:       if (($env{'form.grade_target'} eq 'web') ||
 1635: 	  ($env{'form.grade_target'} eq 'tex') ) {
 1636: 	return $env{'form.grade_target'}
 1637:       } else {
 1638: 	return 'web';
 1639:       }
 1640:     } else {
 1641:       return 'web';
 1642:     }
 1643:   } elsif ($env{'request.state'} eq 'construct') {
 1644:     if ( defined($env{'form.grade_target'})) {
 1645:       return ($env{'form.grade_target'});
 1646:     } else {
 1647:       return 'web';
 1648:     }
 1649:   } else {
 1650:     return 'web';
 1651:   }
 1652: }
 1653: 
 1654: sub handler {
 1655:     my $request=shift;
 1656:     
 1657:     my $target=&get_target();
 1658:     
 1659:     $Apache::lonxml::debug=$env{'user.debug'};
 1660:     
 1661:     &Apache::loncommon::content_type($request,'text/html');
 1662:     &Apache::loncommon::no_cache($request);
 1663:     if ($env{'request.state'} eq 'published') {
 1664: 	$request->set_last_modified(&Apache::lonnet::metadata($request->uri,
 1665: 							      'lastrevisiondate'));
 1666:     }
 1667:     $request->send_http_header;
 1668:     
 1669:     return OK if $request->header_only;
 1670: 
 1671: 
 1672:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1673:     my $filetype;
 1674:     if ($file =~ /\.sty$/) {
 1675: 	$filetype='sty';
 1676:     } else {
 1677: 	$filetype='html';
 1678:     }
 1679: #
 1680: # Edit action? Save file.
 1681: #
 1682:     if (!($env{'request.state'} eq 'published')) {
 1683: 	if ($env{'form.savethisfile'} || $env{'form.viewmode'} || $env{'form.Undo'}) {
 1684: 	    my $html_file=&Apache::lonnet::getfile($file);
 1685: 	    my $error = &Apache::lonhomework::handle_save_or_undo($request, \$html_file, \$env{'form.filecont'});
 1686:             if ($env{'form.savethisfile'}) {
 1687:                 $env{'form.editmode'}='Edit'; #force edit mode
 1688:             }
 1689: 	}
 1690:     }
 1691:     my %mystyle;
 1692:     my $result = '';
 1693:     my $filecontents=&Apache::lonnet::getfile($file);
 1694:     if ($filecontents eq -1) {
 1695: 	my $start_page=&Apache::loncommon::start_page('File Error');
 1696: 	my $end_page=&Apache::loncommon::end_page();
 1697: 	my $fnf=&mt('File not found');
 1698: 	$result=(<<ENDNOTFOUND);
 1699: $start_page
 1700: <b>$fnf: $file</b>
 1701: $end_page
 1702: ENDNOTFOUND
 1703:         $filecontents='';
 1704: 	if ($env{'request.state'} ne 'published') {
 1705: 	    if ($filetype eq 'sty') {
 1706: 		$filecontents=&createnewsty();
 1707: 	    } else {
 1708: 		$filecontents=&createnewhtml();
 1709: 	    }
 1710: 	    $env{'form.editmode'}='Edit'; #force edit mode
 1711: 	}
 1712:     } else {
 1713: 	unless ($env{'request.state'} eq 'published') {
 1714: 	    if ($filecontents=~/BEGIN LON-CAPA Internal/) {
 1715: 		&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.'));
 1716: 	    }
 1717: #
 1718: # we are in construction space, see if edit mode forced
 1719:             &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1720: 						    ['editmode']);
 1721: 	}
 1722: 	if (!$env{'form.editmode'} || $env{'form.viewmode'} || $env{'form.discardview'}) {
 1723: 	    &Apache::structuretags::reset_problem_globals();
 1724: 	    $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
 1725: 						'',%mystyle);
 1726: 	    # .html files may contain <problem> or <Task> need to clean
 1727: 	    # up if it did
 1728: 	    &Apache::structuretags::reset_problem_globals();
 1729: 	    &Apache::lonhomework::finished_parsing();
 1730: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1731: 						    ['rawmode']);
 1732: 	    if ($env{'form.rawmode'}) { $result = $filecontents; }
 1733: 	    if ($filetype eq 'sty') {
 1734: 		my $controls =
 1735: 		    ($env{'request.state'} eq 'construct') ? &Apache::londefdef::edit_controls()
 1736: 		                                           : '';
 1737: 		my %options = ('bgcolor' => '#FFFFFF');
 1738: 		$result = 
 1739: 		    &Apache::loncommon::start_page(undef,undef,\%options).
 1740: 		    $controls.
 1741: 		    $result.
 1742: 		    &Apache::loncommon::end_page();
 1743: 	    }
 1744: 	}
 1745:     }
 1746: 
 1747: #
 1748: # Edit action? Insert editing commands
 1749: #
 1750:     unless ($env{'request.state'} eq 'published') {
 1751: 	if ($env{'form.editmode'} && (!($env{'form.viewmode'})) && (!($env{'form.discardview'})))
 1752: 	{
 1753: 	    my $displayfile=$request->uri;
 1754: 	    $displayfile=~s/^\/[^\/]*//;
 1755: 
 1756: 	    my ($edit_info, $add_to_onload, $add_to_onresize)=
 1757: 		&inserteditinfo($filecontents,$filetype,$displayfile);
 1758: 
 1759: 	    my %options = 
 1760: 		('add_entries' =>
 1761:                    {'onresize' => $add_to_onresize,
 1762: 		    'onload'   => $add_to_onload,   });
 1763: 
 1764: 	    if ($env{'environment.remote'} ne 'off') {
 1765: 		$options{'bgcolor'}   = '#FFFFFF';
 1766: 		$options{'only_body'} = 1;
 1767: 	    }
 1768: 	    my $js =
 1769: 		&Apache::edit::js_change_detection().
 1770: 		&Apache::loncommon::resize_textarea_js();
 1771: 	    my $start_page = &Apache::loncommon::start_page(undef,$js,
 1772: 							    \%options);
 1773: 	    $result=$start_page.
 1774: 		&Apache::lonxml::message_location().
 1775: 		$edit_info.
 1776: 		&Apache::loncommon::end_page();
 1777: 	}
 1778:     }
 1779:     if ($filetype eq 'html') { &writeallows($request->uri); }
 1780:     
 1781:     &Apache::lonxml::add_messages(\$result);
 1782:     $request->print($result);
 1783:     
 1784:     return OK;
 1785: }
 1786: 
 1787: sub display_title {
 1788:     my $result;
 1789:     if ($env{'request.state'} eq 'construct') {
 1790: 	my $title=&Apache::lonnet::gettitle();
 1791: 	if (!defined($title) || $title eq '') {
 1792: 	    $title = $env{'request.filename'};
 1793: 	    $title = substr($title, rindex($title, '/') + 1);
 1794: 	}
 1795:         $result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA "
 1796:                   .&mt('Construction Space')."';</script>";
 1797:     }
 1798:     return $result;
 1799: }
 1800: 
 1801: sub debug {
 1802:     if ($Apache::lonxml::debug eq "1") {
 1803: 	$|=1;
 1804: 	my $request=$Apache::lonxml::request;
 1805: 	if (!$request) {
 1806: 	    eval { $request=Apache->request; };
 1807: 	}
 1808: 	if (!$request) {
 1809: 	    eval { $request=Apache2::RequestUtil->request; };
 1810: 	}
 1811: 	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
 1812: 	#&Apache::lonnet::logthis($_[0]);
 1813:     }
 1814: }
 1815: 
 1816: sub show_error_warn_msg {
 1817:     if ($env{'request.filename'} eq '/home/httpd/html/res/lib/templates/simpleproblem.problem' &&
 1818: 	&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
 1819: 	return 1;
 1820:     }
 1821:     return (($Apache::lonxml::debug eq 1) ||
 1822: 	    ($env{'request.state'} eq 'construct') ||
 1823: 	    ($Apache::lonhomework::browse eq 'F'
 1824: 	     &&
 1825: 	     $env{'form.show_errors'} eq 'on'));
 1826: }
 1827: 
 1828: sub error {
 1829:     my @errors = @_;
 1830: 
 1831:     $errorcount++;
 1832: 
 1833:     if (defined($Apache::inputtags::part)) {
 1834: 	if ( @Apache::inputtags::response ) {
 1835: 	    push(@errors,
 1836: 		 &mt("This error occurred while processing response [_1] in part [_2]",
 1837: 		     $Apache::inputtags::response[-1],
 1838: 		     $Apache::inputtags::part));
 1839: 	} else {
 1840: 	    push(@errors,
 1841: 		 &mt("This error occurred while processing part [_1]",
 1842: 		     $Apache::inputtags::part));
 1843: 	}
 1844:     }
 1845: 
 1846:     if ( &show_error_warn_msg() ) {
 1847: 	# If printing in construction space, put the error inside <pre></pre>
 1848: 	push(@Apache::lonxml::error_messages,
 1849: 	     $Apache::lonxml::warnings_error_header
 1850:              .'<div class="LC_error">'
 1851:              .'<b>'.&mt('ERROR:').' </b>'.join("<br />\n",@errors)
 1852:              ."</div>\n");
 1853: 	$Apache::lonxml::warnings_error_header='';
 1854:     } else {
 1855: 	my $errormsg;
 1856: 	my ($symb)=&Apache::lonnet::symbread();
 1857: 	if ( !$symb ) {
 1858: 	    #public or browsers
 1859: 	    $errormsg=&mt("An error occurred while processing this resource. The author has been notified.");
 1860: 	}
 1861: 	my $host=$Apache::lonnet::perlvar{'lonHostID'};
 1862: 	push(@errors,
 1863:         &mt("The error occurred on host [_1]",
 1864:              "<tt>$host</tt>"));
 1865: 
 1866: 	my $msg = join('<br />', @errors);
 1867: 
 1868: 	#notify author
 1869: 	&Apache::lonmsg::author_res_msg($env{'request.filename'},$msg);
 1870: 	#notify course
 1871: 	if ( $symb && $env{'request.course.id'} ) {
 1872: 	    my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1873: 	    my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1874: 	    my (undef,%users)=&Apache::lonmsg::decide_receiver(undef,0,1,1,1);
 1875: 	    my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
 1876:             my $baseurl = &Apache::lonnet::clutter($declutter);
 1877: 	    my @userlist;
 1878: 	    foreach (keys %users) {
 1879: 		my ($user,$domain) = split(/:/, $_);
 1880: 		push(@userlist,"$user\@$domain");
 1881: 		my $key=$declutter.'_'.$user.'_'.$domain;
 1882: 		my %lastnotified=&Apache::lonnet::get('nohist_xmlerrornotifications',
 1883: 						      [$key],
 1884: 						      $cdom,$cnum);
 1885: 		my $now=time;
 1886: 		if ($now-$lastnotified{$key}>86400) {
 1887:                     my $title = &Apache::lonnet::gettitle($symb);
 1888:                     my $sentmessage;
 1889: 		    &Apache::lonmsg::user_normal_msg($user,$domain,
 1890: 		        "Error [$title]",$msg,'',$baseurl,'','',
 1891:                         \$sentmessage,$symb,$title,1);
 1892: 		    &Apache::lonnet::put('nohist_xmlerrornotifications',
 1893: 					 {$key => $now},
 1894: 					 $cdom,$cnum);		
 1895: 		}
 1896: 	    }
 1897: 	    if ($env{'request.role.adv'}) {
 1898: 		$errormsg=&mt("An error occurred while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
 1899: 	    } else {
 1900: 		$errormsg=&mt("An error occurred while processing this resource. The instructor has been notified.");
 1901: 	    }
 1902: 	}
 1903: 	push(@Apache::lonxml::error_messages,"<b>$errormsg</b> <br />");
 1904:     }
 1905: }
 1906: 
 1907: sub warning {
 1908:     $warningcount++;
 1909:   
 1910:     if ($env{'form.grade_target'} ne 'tex') {
 1911: 	if ( &show_error_warn_msg() ) {
 1912: 	    push(@Apache::lonxml::warning_messages,
 1913: 		 $Apache::lonxml::warnings_error_header
 1914:                 .'<div class="LC_warning">'
 1915:                 .&mt('[_1]W[_2]ARNING','<b>','</b>')."<b>:</b> ".join('<br />',@_)
 1916:                 ."</div>\n"
 1917:                 );
 1918: 	    $Apache::lonxml::warnings_error_header='';
 1919: 	}
 1920:     }
 1921: }
 1922: 
 1923: sub info {
 1924:     if ($env{'form.grade_target'} ne 'tex' 
 1925: 	&& $env{'request.state'} eq 'construct') {
 1926: 	push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
 1927:     }
 1928: }
 1929: 
 1930: sub message_location {
 1931:     return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
 1932: }
 1933: 
 1934: sub add_messages {
 1935:     my ($msg)=@_;
 1936:     my $result=join(' ',
 1937: 		    @Apache::lonxml::info_messages,
 1938: 		    @Apache::lonxml::error_messages,
 1939: 		    @Apache::lonxml::warning_messages);
 1940:     undef(@Apache::lonxml::info_messages);
 1941:     undef(@Apache::lonxml::error_messages);
 1942:     undef(@Apache::lonxml::warning_messages);
 1943:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
 1944:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
 1945: }
 1946: 
 1947: sub get_param {
 1948:     my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1949:     if ( ! $context ) { $context = -1; }
 1950:     my $args ='';
 1951:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1952:     if ( ! $Apache::lonxml::usestyle ) {
 1953: 	$args=$Apache::lonxml::style_values.$args;
 1954:     }
 1955:     if ( ! $args ) { return undef; }
 1956:     if ( $case_insensitive ) {
 1957: 	if ($args =~ s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei) {
 1958: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1959:                                      $safeeval); #'
 1960: 	} else {
 1961: 	    return undef;
 1962: 	}
 1963:     } else {
 1964: 	if ( $args =~ /my .*\$\Q$param\E[,\)]/ ) {
 1965: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1966:                                      $safeeval); #'
 1967: 	} else {
 1968: 	    return undef;
 1969: 	}
 1970:     }
 1971: }
 1972: 
 1973: sub get_param_var {
 1974:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1975:   if ( ! $context ) { $context = -1; }
 1976:   my $args ='';
 1977:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1978:   if ( ! $Apache::lonxml::usestyle ) {
 1979:       $args=$Apache::lonxml::style_values.$args;
 1980:   }
 1981:   &Apache::lonxml::debug("Args are $args param is $param");
 1982:   if ($case_insensitive) {
 1983:       if (! ($args=~s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei)) {
 1984: 	  return undef;
 1985:       }
 1986:   } elsif ( $args !~ /my .*\$\Q$param\E[,\)]/ ) { return undef; }
 1987:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1988:   &Apache::lonxml::debug("first run is $value");
 1989:   if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
 1990:       &Apache::lonxml::debug("doing second");
 1991:       my @result=&Apache::run::run("return $value",$safeeval,1);
 1992:       if (!defined($result[0])) {
 1993: 	  return $value
 1994:       } else {
 1995: 	  if (wantarray) { return @result; } else { return $result[0]; }
 1996:       }
 1997:   } else {
 1998:     return $value;
 1999:   }
 2000: }
 2001: 
 2002: sub register_insert_xml {
 2003:     my $parser = HTML::LCParser->new($Apache::lonnet::perlvar{'lonTabDir'}
 2004: 				     .'/insertlist.xml');
 2005:     my ($tagnum,$in_help)=(0,0);
 2006:     my @alltags;
 2007:     my $tag;
 2008:     while (my $token = $parser->get_token()) {
 2009: 	if ($token->[0] eq 'S') {
 2010: 	    my $key;
 2011: 	    if      ($token->[1] eq 'tag') {
 2012: 		$tag = $token->[2]{'name'};
 2013: 		$insertlist{"$tagnum.tag"} = $tag;
 2014: 		$insertlist{"$tag.num"}   = $tagnum;
 2015: 		push(@alltags,$tag);
 2016: 	    } elsif ($in_help && $token->[1] eq 'file') {
 2017: 		$key = $tag.'.helpfile';
 2018: 	    } elsif ($in_help && $token->[1] eq 'description') {
 2019: 		$key = $tag.'.helpdesc';
 2020: 	    } elsif ($token->[1] eq 'description' ||
 2021: 		     $token->[1] eq 'color'       ||
 2022: 		     $token->[1] eq 'show'          ) {
 2023: 		$key = $tag.'.'.$token->[1];
 2024: 	    } elsif ($token->[1] eq 'insert_sub') {
 2025: 		$key = $tag.'.function';
 2026: 	    } elsif ($token->[1] eq 'help') {
 2027: 		$in_help=1;
 2028: 	    } elsif ($token->[1] eq 'allow') {
 2029: 		$key = $tag.'.allow';
 2030: 	    }
 2031: 	    if (defined($key)) {
 2032: 		$insertlist{$key} = $parser->get_text();
 2033: 		$insertlist{$key} =~ s/(^\s*|\s*$ )//gx;
 2034: 	    }
 2035: 	} elsif ($token->[0] eq 'E') {
 2036: 	    if      ($token->[1] eq 'tag') {
 2037: 		undef($tag);
 2038: 		$tagnum++;
 2039: 	    } elsif ($token->[1] eq 'help') {
 2040: 		undef($in_help);
 2041: 	    }
 2042: 	}
 2043:     }
 2044:     
 2045:     # parse the allows and ignore tags set to <show>no</show>
 2046:     foreach my $tag (@alltags) {	
 2047:         next if (!exists($insertlist{"$tag.allow"}));
 2048: 	my $allow =  $insertlist{"$tag.allow"};
 2049:        	foreach my $element (split(',',$allow)) {
 2050: 	    $element =~ s/(^\s*|\s*$ )//gx;
 2051: 	    if (!exists($insertlist{"$element.show"})
 2052:                 || $insertlist{"$element.show"} ne 'no') {
 2053: 		push(@{ $insertlist{$tag.'.which'} },$element);
 2054: 	    }
 2055: 	}
 2056:     }
 2057: }
 2058: 
 2059: sub register_insert {
 2060:     return &register_insert_xml(@_);
 2061: #    &dump_insertlist('2');
 2062: }
 2063: 
 2064: sub dump_insertlist {
 2065:     my ($ext) = @_;
 2066:     open(XML,">/tmp/insertlist.xml.$ext");
 2067:     print XML ("<insertlist>");
 2068:     my $i=0;
 2069: 
 2070:     while (exists($insertlist{"$i.tag"})) {
 2071: 	my $tag = $insertlist{"$i.tag"};
 2072: 	print XML ("
 2073: \t<tag name=\"$tag\">");
 2074: 	if (defined($insertlist{"$tag.description"})) {
 2075: 	    print XML ("
 2076: \t\t<description>".$insertlist{"$tag.description"}."</description>");
 2077: 	}
 2078: 	if (defined($insertlist{"$tag.color"})) {
 2079: 	    print XML ("
 2080: \t\t<color>".$insertlist{"$tag.color"}."</color>");
 2081: 	}
 2082: 	if (defined($insertlist{"$tag.function"})) {
 2083: 	    print XML ("
 2084: \t\t<insert_sub>".$insertlist{"$tag.function"}."</insert_sub>");
 2085: 	}
 2086: 	if (defined($insertlist{"$tag.show"})
 2087: 	    && $insertlist{"$tag.show"} ne 'yes') {
 2088: 	    print XML ("
 2089: \t\t<show>".$insertlist{"$tag.show"}."</show>");
 2090: 	}
 2091: 	if (defined($insertlist{"$tag.helpfile"})) {
 2092: 	    print XML ("
 2093: \t\t<help>
 2094: \t\t\t<file>".$insertlist{"$tag.helpfile"}."</file>");
 2095: 	    if ($insertlist{"$tag.helpdesc"} ne '') {
 2096: 		print XML ("
 2097: \t\t\t<description>".$insertlist{"$tag.helpdesc"}."</description>");
 2098: 	    }
 2099: 	    print XML ("
 2100: \t\t</help>");
 2101: 	}
 2102: 	if (defined($insertlist{"$tag.which"})) {
 2103: 	    print XML ("
 2104: \t\t<allow>".join(',',sort(@{ $insertlist{"$tag.which"} }))."</allow>");
 2105: 	}
 2106: 	print XML ("
 2107: \t</tag>");
 2108: 	$i++;
 2109:     }
 2110:     print XML ("\n</insertlist>\n");
 2111:     close(XML);
 2112: }
 2113: 
 2114: sub description {
 2115:     my ($token)=@_;
 2116:     my $tag = &get_tag($token);
 2117:     return $insertlist{$tag.'.description'};
 2118: }
 2119: 
 2120: # Returns a list containing the help file, and the description
 2121: sub helpinfo {
 2122:     my ($token)=@_;
 2123:     my $tag = &get_tag($token);
 2124:     return ($insertlist{$tag.'.helpfile'}, $insertlist{$tag.'.helpdesc'});
 2125: }
 2126: 
 2127: sub get_tag {
 2128:     my ($token)=@_;
 2129:     my $tagnum;
 2130:     my $tag=$token->[1];
 2131:     foreach my $namespace (reverse(@Apache::lonxml::namespace)) {
 2132: 	my $testtag = $namespace.'::'.$tag;
 2133: 	$tagnum = $insertlist{"$testtag.num"};
 2134: 	last if (defined($tagnum));
 2135:     }
 2136:     if (!defined($tagnum)) {
 2137: 	$tagnum = $Apache::lonxml::insertlist{"$tag.num"};
 2138:     }
 2139:     return $insertlist{"$tagnum.tag"};
 2140: }
 2141: 
 2142: 1;
 2143: __END__
 2144: 
 2145: 

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