File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.442: download - view: text, annotated - select for diffs
Sat Apr 7 00:04:40 2007 UTC (17 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- xml mode of insertlist was not respecting the <show> setting

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

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