File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.459: download - view: text, annotated - select for diffs
Tue Sep 11 23:53:13 2007 UTC (16 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#4816, implementing the <translated> idea

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

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