File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.416: download - view: text, annotated - select for diffs
Thu Sep 14 21:52:36 2006 UTC (17 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- fixing the english

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

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