File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.462: download - view: text, annotated - select for diffs
Mon Oct 8 09:20:22 2007 UTC (16 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
BZ 4074
Add support for maintaining the counters for the number of bubble
lines required per response in exam mode.

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

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