File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.446: download - view: text, annotated - select for diffs
Thu May 17 21:00:59 2007 UTC (17 years ago) by albertel
Branches: MAIN
CVS tags: version_2_4_0, version_2_3_99_0, HEAD
- show insertables by default

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

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