File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.359: download - view: text, annotated - select for diffs
Mon Feb 28 22:21:40 2005 UTC (19 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- my imperfection nows no bounds

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

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