File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.395: download - view: text, annotated - select for diffs
Fri Jan 13 10:33:25 2006 UTC (18 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: version_2_1_X, version_2_1_3, version_2_1_2, version_2_1_1, HEAD
- make rawmode actually work

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

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