File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.382: download - view: text, annotated - select for diffs
Wed Sep 14 19:20:23 2005 UTC (18 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: version_2_0_X, version_2_0_2, HEAD
- preserver CDATA sections as such

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

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