File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.494.4.2: download - view: text, annotated - select for diffs
Sun Oct 4 03:40:13 2009 UTC (14 years, 7 months ago) by raeburn
Branches: version_2_9_X
CVS tags: GCI_2
Diff to branchpoint 1.494: preferred, unified
- Backport 1.499.

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.494.4.2 2009/10/04 03:40:13 raeburn 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: =pod
   41: 
   42: =head1 NAME
   43: 
   44: Apache::lonxml
   45: 
   46: =head1 SYNOPSIS
   47: 
   48: XML Parsing Module
   49: 
   50: This is part of the LearningOnline Network with CAPA project
   51: described at http://www.lon-capa.org.
   52: 
   53: 
   54: =head1 SUBROUTINES
   55: 
   56: =cut
   57: 
   58: 
   59: 
   60: package Apache::lonxml; 
   61: use vars 
   62: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $errorcount $warningcount);
   63: use strict;
   64: use LONCAPA;
   65: use HTML::LCParser();
   66: use HTML::TreeBuilder();
   67: use HTML::Entities();
   68: use Safe();
   69: use Safe::Hole();
   70: use Math::Cephes();
   71: use Math::Random();
   72: use Opcode();
   73: use POSIX qw(strftime);
   74: use Time::HiRes qw( gettimeofday tv_interval );
   75: use Symbol();
   76: 
   77: sub register {
   78:   my ($space,@taglist) = @_;
   79:   foreach my $temptag (@taglist) {
   80:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
   81:   }
   82: }
   83: 
   84: sub deregister {
   85:   my ($space,@taglist) = @_;
   86:   foreach my $temptag (@taglist) {
   87:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
   88:     if ($tempspace eq $space) {
   89:       pop(@{ $Apache::lonxml::alltags{$temptag} });
   90:     }
   91:   }
   92:   #&printalltags();
   93: }
   94: 
   95: use Apache::Constants qw(:common);
   96: use Apache::lontexconvert();
   97: use Apache::style();
   98: use Apache::run();
   99: use Apache::londefdef();
  100: use Apache::scripttag();
  101: use Apache::languagetags();
  102: use Apache::edit();
  103: use Apache::inputtags();
  104: use Apache::outputtags();
  105: use Apache::lonnet;
  106: use Apache::File();
  107: use Apache::loncommon();
  108: use Apache::lonfeedback();
  109: use Apache::lonmsg();
  110: use Apache::loncacc();
  111: use Apache::lonmaxima();
  112: use Apache::lonr();
  113: use Apache::lonlocal;
  114: 
  115: #====================================   Main subroutine: xmlparse  
  116: 
  117: #debugging control, to turn on debugging modify the correct handler
  118: 
  119: $Apache::lonxml::debug=0;
  120: 
  121: # keeps count of the number of warnings and errors generated in a parse
  122: $warningcount=0;
  123: $errorcount=0;
  124: 
  125: #path to the directory containing the file currently being processed
  126: @pwd=();
  127: 
  128: #these two are used for capturing a subset of the output for later processing,
  129: #don't touch them directly use &startredirection and &endredirection
  130: @outputstack = ();
  131: $redirection = 0;
  132: 
  133: #controls wheter the <import> tag actually does
  134: $import = 1;
  135: @extlinks=();
  136: 
  137: # meta mode is a bit weird only some output is to be turned off
  138: #<output> tag turns metamode off (defined in londefdef.pm)
  139: $metamode = 0;
  140: 
  141: # turns on and of run::evaluate actually derefencing var refs
  142: $evaluate = 1;
  143: 
  144: # data structure for eidt mode, determines what tags can go into what other tags
  145: %insertlist=();
  146: 
  147: # stores the list of active tag namespaces
  148: @namespace=();
  149: 
  150: # stores all Scrit Vars displays for later showing
  151: my @script_var_displays=();
  152: 
  153: # a pointer the the Apache request object
  154: $Apache::lonxml::request='';
  155: 
  156: # a problem number counter, and check on ether it is used
  157: $Apache::lonxml::counter=1;
  158: $Apache::lonxml::counter_changed=0;
  159: 
  160: # Part counter hash.   In analysis mode, the
  161: # problems can use this to record which parts increment the counter
  162: # by how much.  The counter subs will maintain this hash via
  163: # their optional part parameters.  Note that the assumption is that
  164: # analysis is done in one request and therefore it is not necessary to
  165: # save this information request-to-request.
  166: 
  167: 
  168: %Apache::lonxml::counters_per_part = ();
  169: 
  170: #internal check on whether to look at style defs
  171: $Apache::lonxml::usestyle=1;
  172: 
  173: #locations used to store the parameter string for style substitutions
  174: $Apache::lonxml::style_values='';
  175: $Apache::lonxml::style_end_values='';
  176: 
  177: #array of ssi calls that need to occur after we are done parsing
  178: @Apache::lonxml::ssi_info=();
  179: 
  180: #should we do the postag variable interpolation
  181: $Apache::lonxml::post_evaluate=1;
  182: 
  183: #a header message to emit in the case of any generated warning or errors
  184: $Apache::lonxml::warnings_error_header='';
  185: 
  186: #  Control whether or not LaTeX symbols should be substituted for their
  187: #  \ style equivalents...this may be turned off e.g. in an verbatim
  188: #  environment.
  189: 
  190: $Apache::lonxml::substitute_LaTeX_symbols = 1; # Starts out on.
  191: 
  192: sub enable_LaTeX_substitutions {
  193:     $Apache::lonxml::substitute_LaTeX_symbols = 1;
  194: }
  195: sub disable_LaTeX_substitutions {
  196:     $Apache::lonxml::substitute_LaTeX_symbols = 0;
  197: }
  198: 
  199: sub xmlend {
  200:     my ($target,$parser)=@_;
  201:     my $mode='xml';
  202:     my $status='OPEN';
  203:     if ($Apache::lonhomework::parsing_a_problem ||
  204: 	$Apache::lonhomework::parsing_a_task ) {
  205: 	$mode='problem';
  206: 	$status=$Apache::inputtags::status[-1]; 
  207:     }
  208:     my $discussion;
  209:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  210: 					   ['LONCAPA_INTERNAL_no_discussion']);
  211:     if (! exists($env{'form.LONCAPA_INTERNAL_no_discussion'}) ||
  212:         $env{'form.LONCAPA_INTERNAL_no_discussion'} ne 'true') {
  213:         $discussion=&Apache::lonfeedback::list_discussion($mode,$status);
  214:     }
  215:     if ($target eq 'tex') {
  216: 	$discussion.='<tex>\keephidden{ENDOFPROBLEM}\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\end{document}</tex>';
  217: 	&Apache::lonxml::newparser($parser,\$discussion,'');
  218: 	return '';
  219:     }
  220: 
  221:     return $discussion;
  222: }
  223: 
  224: sub tokeninputfield {
  225:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
  226:     $defhost=~tr/a-z/A-Z/;
  227:     return (<<ENDINPUTFIELD)
  228: <script type="text/javascript">
  229:     function updatetoken() {
  230: 	var comp=new Array;
  231:         var barcode=unescape(document.tokeninput.barcode.value);
  232:         comp=barcode.split('*');
  233:         if (typeof(comp[0])!="undefined") {
  234: 	    document.tokeninput.codeone.value=comp[0];
  235: 	}
  236:         if (typeof(comp[1])!="undefined") {
  237: 	    document.tokeninput.codetwo.value=comp[1];
  238: 	}
  239:         if (typeof(comp[2])!="undefined") {
  240:             comp[2]=comp[2].toUpperCase();
  241: 	    document.tokeninput.codethree.value=comp[2];
  242: 	}
  243:         document.tokeninput.barcode.value='';
  244:     }  
  245: </script>
  246: <form method="post" name="tokeninput">
  247: <table border="2" bgcolor="#FFFFBB">
  248: <tr><th>DocID Checkin</th></tr>
  249: <tr><td>
  250: <table>
  251: <tr>
  252: <td>Scan in Barcode</td>
  253: <td><input type="text" size="22" name="barcode" 
  254: onChange="updatetoken()"/></td>
  255: </tr>
  256: <tr><td><i>or</i> Type in DocID</td>
  257: <td>
  258: <input type="text" size="5" name="codeone" />
  259: <b><font size="+2">*</font></b>
  260: <input type="text" size="5" name="codetwo" />
  261: <b><font size="+2">*</font></b>
  262: <input type="text" size="10" name="codethree" value="$defhost" 
  263: onChange="this.value=this.value.toUpperCase()" />
  264: </td></tr>
  265: </table>
  266: </td></tr>
  267: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
  268: </table>
  269: </form>
  270: ENDINPUTFIELD
  271: }
  272: 
  273: sub maketoken {
  274:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  275:     unless ($symb) {
  276: 	$symb=&Apache::lonnet::symbread();
  277:     }
  278:     unless ($tuname) {
  279: 	$tuname=$env{'user.name'};
  280:         $tudom=$env{'user.domain'};
  281:         $tcrsid=$env{'request.course.id'};
  282:     }
  283: 
  284:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
  285: }
  286: 
  287: sub printtokenheader {
  288:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
  289:     unless ($token) { return ''; }
  290: 
  291:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
  292:     unless ($tsymb) {
  293: 	$tsymb=$symb;
  294:     }
  295:     unless ($tuname) {
  296: 	$tuname=$name;
  297:         $tudom=$domain;
  298:         $tcrsid=$courseid;
  299:     }
  300: 
  301:     my $plainname=&Apache::loncommon::plainname($tuname,$tudom);
  302: 
  303:     if ($target eq 'web') {
  304:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
  305: 	return 
  306:  '<img align="right" src="/cgi-bin/barcode.png?encode='.$token.'" />'.
  307:                &mt('Checked out for').' '.$plainname.
  308:                '<br />'.&mt('User').': '.$tuname.' at '.$tudom.
  309: 	       '<br />'.&mt('ID').': '.$idhash{$tuname}.
  310: 	       '<br />'.&mt('CourseID').': '.$tcrsid.
  311: 	       '<br />'.&mt('Course').': '.$env{'course.'.$tcrsid.'.description'}.
  312:                '<br />'.&mt('DocID').': '.$token.
  313:                '<br />'.&mt('Time').': '.&Apache::lonlocal::locallocaltime().'<hr />';
  314:     } else {
  315:         return $token;
  316:     }
  317: }
  318: 
  319: sub printalltags {
  320:   my $temp;
  321:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  322:     &Apache::lonxml::debug("$temp -- ".
  323: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
  324:   }
  325: }
  326: 
  327: sub xmlparse {
  328:  my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
  329: 
  330:  &setup_globals($request,$target);
  331:  &Apache::inputtags::initialize_inputtags();
  332:  &Apache::bridgetask::initialize_bridgetask();
  333:  &Apache::outputtags::initialize_outputtags();
  334:  &Apache::edit::initialize_edit();
  335:  &Apache::londefdef::initialize_londefdef();
  336: 
  337: #
  338: # do we have a course style file?
  339: #
  340: 
  341:  if ($env{'request.course.id'} && $env{'request.state'} ne 'construct') {
  342:      my $bodytext=
  343: 	 $env{'course.'.$env{'request.course.id'}.'.default_xml_style'};
  344:      if ($bodytext) {
  345: 	 foreach my $file (split(',',$bodytext)) {
  346: 	     my $location=&Apache::lonnet::filelocation('',$file);
  347: 	     my $styletext=&Apache::lonnet::getfile($location);
  348: 	     if ($styletext ne '-1') {
  349: 		 %style_for_target = (%style_for_target,
  350: 				      &Apache::style::styleparser($target,$styletext));
  351: 	     }
  352: 	 }
  353:      }
  354:  } elsif ($env{'construct.style'}
  355: 	  && ($env{'request.state'} eq 'construct')) {
  356:      my $location=&Apache::lonnet::filelocation('',$env{'construct.style'});
  357:      my $styletext=&Apache::lonnet::getfile($location);
  358:      if ($styletext ne '-1') {
  359: 	 %style_for_target = (%style_for_target,
  360: 			      &Apache::style::styleparser($target,$styletext));
  361:      }
  362:  }
  363: #&printalltags();
  364:  my @pars = ();
  365:  my $pwd=$env{'request.filename'};
  366:  $pwd =~ s:/[^/]*$::;
  367:  &newparser(\@pars,\$content_file_string,$pwd);
  368: 
  369:  my $safeeval = new Safe;
  370:  my $safehole = new Safe::Hole;
  371:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  372: #-------------------- Redefinition of the target in the case of compound target
  373: 
  374:  ($target, my @tenta) = split('&&',$target);
  375: 
  376:  my @stack = ();
  377:  my @parstack = ();
  378:  &initdepth();
  379:  &init_alarm();
  380:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  381: 				   $safeeval,\%style_for_target,1);
  382: 
  383:  if (@stack) {
  384:      &warning(&mt('At end of file some tags were still left unclosed:').
  385: 	      ' <tt>&lt;'.join('&gt;</tt>, <tt>&lt;',reverse(@stack)).
  386: 	      '&gt;</tt>');
  387:  }
  388:  if ($env{'request.uri'}) {
  389:     &writeallows($env{'request.uri'});
  390:  }
  391:  &do_registered_ssi();
  392:  if ($Apache::lonxml::counter_changed) { &store_counter() }
  393: 
  394:  &clean_safespace($safeeval);
  395: 
  396:  if (@script_var_displays) {
  397:      $finaloutput .= join('',@script_var_displays);
  398:      undef(@script_var_displays);
  399:  }
  400:  &init_state();
  401:  if ($env{'form.return_only_error_and_warning_counts'}) {
  402:      if ($env{'request.filename'}=~/\.(html|htm|xml)$/i) { 
  403:         my $error=&verify_html($content_file_string);
  404:         if ($error) { $errorcount++; }
  405:      }
  406:      return "$errorcount:$warningcount";
  407:  }
  408:  return $finaloutput;
  409: }
  410: 
  411: sub latex_special_symbols {
  412:     my ($string,$where)=@_;
  413:     #
  414:     #  If e.g. in verbatim mode, then don't substitute.
  415:     #  but return original string.
  416:     #
  417:     if (!($Apache::lonxml::substitute_LaTeX_symbols)) {
  418: 	return $string;
  419:     }
  420:     if ($where eq 'header') {
  421: 	$string =~ s/\\/\$\\backslash\$/g; # \  -> $\backslash$ per LaTex line by line pg  10.
  422: 	$string =~ s/(\$|%|\{|\})/\\$1/g;
  423: 	$string=&Apache::lonprintout::character_chart($string);
  424: 	# any & or # leftover should be safe to just escape
  425:         $string=~s/([^\\])\&/$1\\\&/g;
  426:         $string=~s/([^\\])\#/$1\\\#/g;
  427: 	$string =~ s/_/\\_/g;              # _ -> \_
  428: 	$string =~ s/\^/\\\^{}/g;          # ^ -> \^{} 
  429:     } else {
  430: 	$string=~s/\\/\\ensuremath{\\backslash}/g;
  431: 	$string=~s/\\\%|\%/\\\%/g;
  432: 	$string=~s/\\{|{/\\{/g;
  433: 	$string=~s/\\}|}/\\}/g;
  434: 	$string=~s/\\ensuremath\\{\\backslash\\}/\\ensuremath{\\backslash}/g;
  435: 	$string=~s/\\\$|\$/\\\$/g;
  436: 	$string=~s/\\\_|\_/\\\_/g;
  437:         $string=~s/([^\\]|^)(\~|\^)/$1\\$2\\strut /g;
  438: 	$string=~s/(>|<)/\\ensuremath\{$1\}/g; #more or less
  439: 	$string=&Apache::lonprintout::character_chart($string);
  440: 	# any & or # leftover should be safe to just escape
  441: 	$string=~s/\\\&|\&/\\\&/g;
  442: 	$string=~s/\\\#|\#/\\\#/g;
  443:         $string=~s/\|/\$\\mid\$/g;
  444: #single { or } How to escape?
  445:     }
  446:     return $string;
  447: }
  448: 
  449: sub inner_xmlparse {
  450:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target,$start)=@_;
  451:   my $finaloutput = '';
  452:   my $result;
  453:   my $token;
  454:   my $dontpop=0;
  455:   my $startredirection = $Apache::lonxml::redirection;
  456:   while ( $#$pars > -1 ) {
  457:     while ($token = $$pars['-1']->get_token) {
  458:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
  459: 	if ($metamode<1) {
  460: 	    my $text=$token->[1];
  461: 	    if ($token->[0] eq 'C' && $target eq 'tex') {
  462: 		$text = '';
  463: #		$text = '%'.$text."\n";
  464: 	    }
  465: 	    $result.=$text;
  466: 	}
  467:       } elsif (($token->[0] eq 'D')) {
  468: 	if ($metamode<1 && $target eq 'web') {
  469: 	    my $text=$token->[1];
  470: 	    $result.=$text;
  471: 	}
  472:       } elsif ($token->[0] eq 'PI') {
  473: 	if ($metamode<1 && $target eq 'web') {
  474: 	  $result=$token->[2];
  475: 	}
  476:       } elsif ($token->[0] eq 'S') {
  477: 	# add tag to stack
  478: 	push (@$stack,$token->[1]);
  479: 	# add parameters list to another stack
  480: 	push (@$parstack,&parstring($token));
  481: 	&increasedepth($token);
  482: 	if ($Apache::lonxml::usestyle &&
  483: 	    exists($$style_for_target{$token->[1]})) {
  484: 	    $Apache::lonxml::usestyle=0;
  485: 	    my $string=$$style_for_target{$token->[1]}.
  486: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
  487: 	    &Apache::lonxml::newparser($pars,\$string);
  488: 	    $Apache::lonxml::style_values=$$parstack[-1];
  489: 	    $Apache::lonxml::style_end_values=$$parstack[-1];
  490: 	} else {
  491: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  492: 			     $parstack, $pars, $safeeval, $style_for_target);
  493: 	}
  494:       } elsif ($token->[0] eq 'E') {
  495: 	if ($Apache::lonxml::usestyle &&
  496: 	    exists($$style_for_target{'/'."$token->[1]"})) {
  497: 	    $Apache::lonxml::usestyle=0;
  498: 	    my $string=$$style_for_target{'/'.$token->[1]}.
  499: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
  500: 	    &Apache::lonxml::newparser($pars,\$string);
  501: 	    $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
  502: 	    $Apache::lonxml::style_end_values='';
  503: 	    $dontpop=1;
  504: 	} else {
  505: 	    #clear out any tags that didn't end
  506: 	    while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  507: 		my $lasttag=$$stack[-1];
  508: 		if ($token->[1] =~ /^\Q$lasttag\E$/i) {
  509: 		    &Apache::lonxml::warning(&mt('Using tag [_1] on line [_2] as end tag to [_3]','&lt;/'.$token->[1].'&gt;','.$token->[3].','&lt;'.$$stack[-1].'&gt;'));
  510: 		    last;
  511: 		} else {
  512:                     &Apache::lonxml::warning(&mt('Found tag [_1] on line [_2] when looking for [_3] in file.','&lt;/'.$token->[1].'&gt;',$token->[3],'&lt;/'.$$stack[-1].'&gt;'));
  513: 		    &end_tag($stack,$parstack,$token);
  514: 		}
  515: 	    }
  516: 	    $result = &callsub("end_$token->[1]", $target, $token, $stack,
  517: 			       $parstack, $pars,$safeeval, $style_for_target);
  518: 	}
  519:       } else {
  520: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  521:       }
  522:       #evaluate variable refs in result
  523:       if ($Apache::lonxml::post_evaluate &&$result ne "") {
  524: 	  my $extras;
  525: 	  if (!$Apache::lonxml::usestyle) {
  526: 	      $extras=$Apache::lonxml::style_values;
  527: 	  }
  528: 	  if ( $#$parstack > -1 ) {
  529: 	      $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
  530: 	  } else {
  531: 	      $result= &Apache::run::evaluate($result,$safeeval,$extras);
  532:           }
  533:       }
  534:       $Apache::lonxml::post_evaluate=1;
  535: 
  536:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  537: 	  #Style file definitions should be correct
  538: 	  if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
  539: 	      $result=&latex_special_symbols($result);
  540: 	  }
  541:       }
  542: 
  543:       if ($Apache::lonxml::redirection) {
  544: 	$Apache::lonxml::outputstack['-1'] .= $result;
  545:       } else {
  546: 	$finaloutput.=$result;
  547:       }
  548:       $result = '';
  549: 
  550:       if ($token->[0] eq 'E' && !$dontpop) {
  551: 	&end_tag($stack,$parstack,$token);
  552:       }
  553:       $dontpop=0;
  554:     }	
  555:     if ($#$pars > -1) {
  556: 	pop @$pars;
  557: 	pop @Apache::lonxml::pwd;
  558:     }
  559:   }
  560: 
  561:   # if ($target eq 'meta') {
  562:   #   $finaloutput.=&endredirection;
  563:   # }
  564: 
  565:   if ( $start && $target eq 'grade') { &endredirection(); }
  566:   if ( $Apache::lonxml::redirection > $startredirection) {
  567:       while ($Apache::lonxml::redirection > $startredirection) {
  568: 	  $finaloutput .= &endredirection();
  569:       }
  570:   }
  571:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  572:     $finaloutput=&afterburn($finaloutput);
  573:   }	    
  574:   return $finaloutput;
  575: }
  576: 
  577: ## 
  578: ## Looks to see if there is a subroutine defined for this tag.  If so, call it,
  579: ## otherwise do not call it as we do not know what it is.
  580: ##
  581: sub callsub {
  582:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  583:   my $currentstring='';
  584:   my $nodefault;
  585:   {
  586:     my $sub1;
  587:     no strict 'refs';
  588:     my $tag=$token->[1];
  589: # get utterly rid of extended html tags
  590:     if ($tag=~/^x\-/i) { return ''; }
  591:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  592:     if (!$space) {
  593:      	$tag=~tr/A-Z/a-z/;
  594: 	$sub=~tr/A-Z/a-z/;
  595: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  596:     }
  597: 
  598:     my $deleted=0;
  599:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  600:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  601: 					     $parstack,$parser,$safeeval,
  602: 					     $style);
  603:     }
  604:     if (!$deleted) {
  605:       if ($space) {
  606: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
  607: 	$sub1="$space\:\:$sub";
  608: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  609: 					     $parstack,$parser,$safeeval,
  610: 					     $style);
  611:       } else {
  612:           if ($target eq 'tex') {
  613:               # throw away tag name
  614:               return '';
  615:           }
  616: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
  617: 	if ($metamode <1) {
  618: 	  if (defined($token->[4]) && ($metamode < 1)) {
  619: 	    $currentstring = $token->[4];
  620: 	  } else {
  621: 	    $currentstring = $token->[2];
  622: 	  }
  623: 	}
  624:       }
  625:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  626:       if ($currentstring eq '' && $nodefault eq '') {
  627: 	if ($target eq 'edit') {
  628: 	  #&Apache::lonxml::debug("doing default edit for $token->[1]");
  629: 	  if ($token->[0] eq 'S') {
  630: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  631: 	  } elsif ($token->[0] eq 'E') {
  632: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  633: 	  }
  634: 	}
  635:       }
  636:       if ($target eq 'modified' && $nodefault eq '') {
  637: 	  if ($currentstring eq '') {
  638: 	      if ($token->[0] eq 'S') {
  639: 		  $currentstring = $token->[4];
  640: 	      } elsif ($token->[0] eq 'E') {
  641: 		  $currentstring = $token->[2];
  642: 	      } else {
  643: 		  $currentstring = $token->[2];
  644: 	      }
  645: 	  }
  646: 	  if ($token->[0] eq 'S') {
  647: 	      $currentstring.=&Apache::edit::handle_insert();
  648: 	  } elsif ($token->[0] eq 'E') {
  649: 	      $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
  650: 	  }
  651:       }
  652:     }
  653:     use strict 'refs';
  654:   }
  655:   return $currentstring;
  656: }
  657: 
  658: {
  659:     my %state;
  660: 
  661:     sub init_state {
  662: 	undef(%state);
  663:     }
  664:     
  665:     sub set_state {
  666: 	my ($key,$value) = @_;
  667: 	$state{$key} = $value;
  668: 	return $value;
  669:     }
  670:     sub get_state {
  671: 	my ($key) = @_;
  672: 	return $state{$key};
  673:     }
  674: }
  675: 
  676: sub setup_globals {
  677:   my ($request,$target)=@_;
  678:   $Apache::lonxml::request=$request;
  679:   $errorcount=0;
  680:   $warningcount=0;
  681:   $Apache::lonxml::internal_error=0;
  682:   $Apache::lonxml::default_homework_loaded=0;
  683:   $Apache::lonxml::usestyle=1;
  684:   &init_counter();
  685:   &clear_bubble_lines_for_part();
  686:   &init_state();
  687:   &set_state('target',$target);
  688:   @Apache::lonxml::pwd=();
  689:   @Apache::lonxml::extlinks=();
  690:   @script_var_displays=();
  691:   @Apache::lonxml::ssi_info=();
  692:   $Apache::lonxml::post_evaluate=1;
  693:   $Apache::lonxml::warnings_error_header='';
  694:   $Apache::lonxml::substitute_LaTeX_symbols = 1;
  695:   if ($target eq 'meta') {
  696:     $Apache::lonxml::redirection = 0;
  697:     $Apache::lonxml::metamode = 1;
  698:     $Apache::lonxml::evaluate = 1;
  699:     $Apache::lonxml::import = 0;
  700:   } elsif ($target eq 'answer') {
  701:     $Apache::lonxml::redirection = 0;
  702:     $Apache::lonxml::metamode = 1;
  703:     $Apache::lonxml::evaluate = 1;
  704:     $Apache::lonxml::import = 1;
  705:   } elsif ($target eq 'grade') {
  706:     &startredirection(); #ended in inner_xmlparse on exit
  707:     $Apache::lonxml::metamode = 0;
  708:     $Apache::lonxml::evaluate = 1;
  709:     $Apache::lonxml::import = 1;
  710:   } elsif ($target eq 'modified') {
  711:     $Apache::lonxml::redirection = 0;
  712:     $Apache::lonxml::metamode = 0;
  713:     $Apache::lonxml::evaluate = 0;
  714:     $Apache::lonxml::import = 0;
  715:   } elsif ($target eq 'edit') {
  716:     $Apache::lonxml::redirection = 0;
  717:     $Apache::lonxml::metamode = 0;
  718:     $Apache::lonxml::evaluate = 0;
  719:     $Apache::lonxml::import = 0;
  720:   } elsif ($target eq 'analyze') {
  721:     $Apache::lonxml::redirection = 0;
  722:     $Apache::lonxml::metamode = 0;
  723:     $Apache::lonxml::evaluate = 1;
  724:     $Apache::lonxml::import = 1;
  725:   } else {
  726:     $Apache::lonxml::redirection = 0;
  727:     $Apache::lonxml::metamode = 0;
  728:     $Apache::lonxml::evaluate = 1;
  729:     $Apache::lonxml::import = 1;
  730:   }
  731: }
  732: 
  733: sub init_safespace {
  734:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  735:   $safeeval->deny_only(':dangerous');
  736:   $safeeval->reval('use Math::Complex;');
  737:   $safeeval->permit_only(":default");
  738:   $safeeval->permit("entereval");
  739:   $safeeval->permit(":base_math");
  740:   $safeeval->permit("sort");
  741:   $safeeval->permit("time");
  742:   $safeeval->permit("caller");
  743:   $safeeval->deny("rand");
  744:   $safeeval->deny("srand");
  745:   $safeeval->deny(":base_io");
  746:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  747:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
  748:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  749:   $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
  750: 		  '&chem_standard_order');
  751:   $safehole->wrap(\&Apache::response::check_status,$safeeval,'&check_status');
  752:   $safehole->wrap(\&Apache::response::implicit_multiplication,$safeeval,'&implicit_multiplication');
  753: 
  754:   $safehole->wrap(\&Apache::lonmaxima::maxima_eval,$safeeval,'&maxima_eval');
  755:   $safehole->wrap(\&Apache::lonmaxima::maxima_check,$safeeval,'&maxima_check');
  756:   $safehole->wrap(\&Apache::lonmaxima::maxima_cas_formula_fix,$safeeval,
  757: 		  '&maxima_cas_formula_fix');
  758: 
  759:   $safehole->wrap(\&Apache::lonr::r_eval,$safeeval,'&r_eval');
  760:   $safehole->wrap(\&Apache::lonr::Rentry,$safeeval,'&Rentry');
  761:   $safehole->wrap(\&Apache::lonr::Rarray,$safeeval,'&Rarray');
  762:   $safehole->wrap(\&Apache::lonr::r_check,$safeeval,'&r_check');
  763:   $safehole->wrap(\&Apache::lonr::r_cas_formula_fix,$safeeval,
  764:                   '&r_cas_formula_fix');
  765:  
  766:   $safehole->wrap(\&Apache::caparesponse::capa_formula_fix,$safeeval,
  767: 		  '&capa_formula_fix');
  768: 
  769:   $safehole->wrap(\&Apache::lonlocal::locallocaltime,$safeeval,
  770:                   '&locallocaltime');
  771: 
  772:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  773:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  774:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  775:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  776:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  777:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  778:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  779:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  780:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  781:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  782:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  783:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  784:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  785:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  786:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  787:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  788:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  789:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  790:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  791:   
  792:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
  793:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
  794:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
  795:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
  796:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
  797:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
  798:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
  799:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
  800:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
  801:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
  802:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
  803:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
  804:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
  805:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
  806:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
  807:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
  808:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
  809:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
  810:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
  811:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
  812:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
  813:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
  814: 
  815:   $safehole->wrap(\&Math::Cephes::Matrix::mat,$safeeval,'&mat');
  816:   $safehole->wrap(\&Math::Cephes::Matrix::new,$safeeval,
  817: 		  '&Math::Cephes::Matrix::new');
  818:   $safehole->wrap(\&Math::Cephes::Matrix::coef,$safeeval,
  819: 		  '&Math::Cephes::Matrix::coef');
  820:   $safehole->wrap(\&Math::Cephes::Matrix::clr,$safeeval,
  821: 		  '&Math::Cephes::Matrix::clr');
  822:   $safehole->wrap(\&Math::Cephes::Matrix::add,$safeeval,
  823: 		  '&Math::Cephes::Matrix::add');
  824:   $safehole->wrap(\&Math::Cephes::Matrix::sub,$safeeval,
  825: 		  '&Math::Cephes::Matrix::sub');
  826:   $safehole->wrap(\&Math::Cephes::Matrix::mul,$safeeval,
  827: 		  '&Math::Cephes::Matrix::mul');
  828:   $safehole->wrap(\&Math::Cephes::Matrix::div,$safeeval,
  829: 		  '&Math::Cephes::Matrix::div');
  830:   $safehole->wrap(\&Math::Cephes::Matrix::inv,$safeeval,
  831: 		  '&Math::Cephes::Matrix::inv');
  832:   $safehole->wrap(\&Math::Cephes::Matrix::transp,$safeeval,
  833: 		  '&Math::Cephes::Matrix::transp');
  834:   $safehole->wrap(\&Math::Cephes::Matrix::simq,$safeeval,
  835: 		  '&Math::Cephes::Matrix::simq');
  836:   $safehole->wrap(\&Math::Cephes::Matrix::mat_to_vec,$safeeval,
  837: 		  '&Math::Cephes::Matrix::mat_to_vec');
  838:   $safehole->wrap(\&Math::Cephes::Matrix::vec_to_mat,$safeeval,
  839: 		  '&Math::Cephes::Matrix::vec_to_mat');
  840:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
  841: 		  '&Math::Cephes::Matrix::check');
  842:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
  843: 		  '&Math::Cephes::Matrix::check');
  844: 
  845: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
  846: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
  847: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
  848: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
  849: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
  850: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
  851: 
  852:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  853:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  854:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  855:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  856:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  857:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  858:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  859:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  860:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  861:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  862:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  863:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  864:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  865:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  866:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  867:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  868:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  869:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  870:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  871:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  872:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  873:   $safehole->wrap(\&Apache::loncommon::languages,$safeeval,'&languages');
  874:   $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
  875:   $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
  876:   $safehole->wrap(\&Apache::lonnet::logthis,$safeeval,'&LONCAPA_INTERNAL_LOGTHIS');
  877:   $safehole->wrap(\&Apache::inputtags::finalizeawards,$safeeval,'&LONCAPA_INTERNAL_FINALIZEAWARDS');
  878:   $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
  879: #  use Data::Dumper;
  880: #  $safehole->wrap(\&Data::Dumper::Dumper,$safeeval,'&LONCAPA_INTERNAL_Dumper');
  881: #need to inspect this class of ops
  882: # $safeeval->deny(":base_orig");
  883:   $safeeval->permit("require");
  884:   $safeinit .= ';$external::target="'.$target.'";';
  885:   &Apache::run::run($safeinit,$safeeval);
  886:   &initialize_rndseed($safeeval);
  887: }
  888: 
  889: sub clean_safespace {
  890:     my ($safeeval) = @_;
  891:     delete_package_recurse($safeeval->{Root});
  892: }
  893: 
  894: sub delete_package_recurse {
  895:      my ($package) = @_;
  896:      my @subp;
  897:      {
  898: 	 no strict 'refs';
  899: 	 while (my ($key,$val) = each(%{*{"$package\::"}})) {
  900: 	     if (!defined($val)) { next; }
  901: 	     local (*ENTRY) = $val;
  902: 	     if (defined *ENTRY{HASH} && $key =~ /::$/ &&
  903: 		 $key ne "main::" && $key ne "<none>::")
  904: 	     {
  905: 		 my ($p) = $package ne "main" ? "$package\::" : "";
  906: 		 ($p .= $key) =~ s/::$//;
  907: 		 push(@subp,$p);
  908: 	     }
  909: 	 }
  910:      }
  911:      foreach my $p (@subp) {
  912: 	 delete_package_recurse($p);
  913:      }
  914:      Symbol::delete_package($package);
  915: }
  916: 
  917: sub initialize_rndseed {
  918:     my ($safeeval)=@_;
  919:     my $rndseed;
  920:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
  921:     $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  922:     my $safeinit = '$external::randomseed="'.$rndseed.'";';
  923:     &Apache::lonxml::debug("Setting rndseed to $rndseed");
  924:     &Apache::run::run($safeinit,$safeeval);
  925: }
  926: 
  927: sub default_homework_load {
  928:     my ($safeeval)=@_;
  929:     &Apache::lonxml::debug('Loading default_homework');
  930:     my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
  931:     if ($default eq -1) {
  932: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
  933:     } else {
  934: 	&Apache::run::run($default,$safeeval);
  935: 	$Apache::lonxml::default_homework_loaded=1;
  936:     }
  937: }
  938: 
  939: {
  940:     my $alarm_depth;
  941:     sub init_alarm {
  942: 	alarm(0);
  943: 	$alarm_depth=0;
  944:     }
  945: 
  946:     sub start_alarm {
  947: 	if ($alarm_depth<1) {
  948: 	    my $old=alarm($Apache::lonnet::perlvar{'lonScriptTimeout'});
  949: 	    if ($old) {
  950: 		&Apache::lonxml::error("Cancelled an alarm of $old, this shouldn't occur.");
  951: 	    }
  952: 	}
  953: 	$alarm_depth++;
  954:     }
  955: 
  956:     sub end_alarm {
  957: 	$alarm_depth--;
  958: 	if ($alarm_depth<1) { alarm(0); }
  959:     }
  960: }
  961: my $metamode_was;
  962: sub startredirection {
  963:     if (!$Apache::lonxml::redirection) {
  964: 	$metamode_was=$Apache::lonxml::metamode;
  965:     }
  966:     $Apache::lonxml::metamode=0;
  967:     $Apache::lonxml::redirection++;
  968:     push (@Apache::lonxml::outputstack, '');
  969: }
  970: 
  971: sub endredirection {
  972:     if (!$Apache::lonxml::redirection) {
  973: 	&Apache::lonxml::error("Endredirection was called before a startredirection, perhaps you have unbalanced tags. Some debugging information:".join ":",caller);
  974: 	return '';
  975:     }
  976:     $Apache::lonxml::redirection--;
  977:     if (!$Apache::lonxml::redirection) {
  978: 	$Apache::lonxml::metamode=$metamode_was;
  979:     }
  980:     pop @Apache::lonxml::outputstack;
  981: }
  982: sub in_redirection {
  983:     return ($Apache::lonxml::redirection > 0)
  984: }
  985: 
  986: sub end_tag {
  987:   my ($tagstack,$parstack,$token)=@_;
  988:   pop(@$tagstack);
  989:   pop(@$parstack);
  990:   &decreasedepth($token);
  991: }
  992: 
  993: sub initdepth {
  994:   @Apache::lonxml::depthcounter=();
  995:   undef($Apache::lonxml::last_depth_count);
  996: }
  997: 
  998: 
  999: my @timers;
 1000: my $lasttime;
 1001: # @Apache::lonxml::depthcounter -> count of tags that exist so
 1002: #                                  far at each level
 1003: # $Apache::lonxml::last_depth_count -> when ascending, need to
 1004: # remember the count for the level below the current level (for
 1005: # example going from 1_2 -> 1 -> 1_3 need to remember the 2 )
 1006: 
 1007: sub increasedepth {
 1008:   my ($token) = @_;
 1009:   push(@Apache::lonxml::depthcounter,$Apache::lonxml::last_depth_count+1);
 1010:   undef($Apache::lonxml::last_depth_count);
 1011:   my $time;
 1012:   if ($Apache::lonxml::debug eq "1") {
 1013:       push(@timers,[&gettimeofday()]);
 1014:       $time=&tv_interval($lasttime);
 1015:       $lasttime=[&gettimeofday()];
 1016:   }
 1017:   my $spacing='  'x($#Apache::lonxml::depthcounter);
 1018:   $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
 1019: #  &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time");
 1020: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
 1021: }
 1022: 
 1023: sub decreasedepth {
 1024:   my ($token) = @_;
 1025:   if (  $#Apache::lonxml::depthcounter == -1) {
 1026:       &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
 1027:   }
 1028:   $Apache::lonxml::last_depth_count = pop(@Apache::lonxml::depthcounter);
 1029: 
 1030:   my ($timer,$time);
 1031:   if ($Apache::lonxml::debug eq "1") {
 1032:       $timer=pop(@timers);
 1033:       $time=&tv_interval($lasttime);
 1034:       $lasttime=[&gettimeofday()];
 1035:   }
 1036:   my $spacing='  'x($#Apache::lonxml::depthcounter);
 1037:   $Apache::lonxml::curdepth = join('_',@Apache::lonxml::depthcounter);
 1038: #  &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time : ".&tv_interval($timer));
 1039: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
 1040: }
 1041: 
 1042: sub get_id {
 1043:     my ($parstack,$safeeval)=@_;
 1044:     my $id= &Apache::lonxml::get_param('id',$parstack,$safeeval);
 1045:     if ($env{'request.state'} eq 'construct' && $id =~ /([._]|[^\w\d\s[:punct:]])/) {
 1046: 	&error(&mt("ID [_1] contains invalid characters, IDs are only allowed to contain letters, numbers, spaces and -",'<tt>'.$id.'</tt>'));
 1047:     }
 1048:     if ($id =~ /^\s*$/) { $id = $Apache::lonxml::curdepth; }
 1049:     return $id;
 1050: }
 1051: 
 1052: sub get_all_text_unbalanced {
 1053: #there is a copy of this in lonpublisher.pm
 1054:     my($tag,$pars)= @_;
 1055:     my $token;
 1056:     my $result='';
 1057:     $tag='<'.$tag.'>';
 1058:     while ($token = $$pars[-1]->get_token) {
 1059: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
 1060: 	    if ($token->[0] eq 'T' && $token->[2]) {
 1061: 		$result.='<![CDATA['.$token->[1].']]>';
 1062: 	    } else {
 1063: 		$result.=$token->[1];
 1064: 	    }
 1065: 	} elsif ($token->[0] eq 'PI') {
 1066: 	    $result.=$token->[2];
 1067: 	} elsif ($token->[0] eq 'S') {
 1068: 	    $result.=$token->[4];
 1069: 	} elsif ($token->[0] eq 'E')  {
 1070: 	    $result.=$token->[2];
 1071: 	}
 1072: 	if ($result =~ /\Q$tag\E/is) {
 1073: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
 1074: 	    #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
 1075: 	    #&Apache::lonxml::debug('Result is :'.$1);
 1076: 	    $redo=$tag.$redo;
 1077: 	    &Apache::lonxml::newparser($pars,\$redo);
 1078: 	    last;
 1079: 	}
 1080:     }
 1081:     return $result
 1082: 
 1083: }
 1084: 
 1085: #########################################################################
 1086: #                                                                       #
 1087: #           bubble line counter management                              #
 1088: #                                                                       #
 1089: #########################################################################
 1090: 
 1091: =pod
 1092: 
 1093: For bubble grading mode and exam bubble printing mode, the tracking of
 1094: the current 'bubble line number' is stored in the %env element
 1095: 'form.counter', and is modifed and handled by the following routines.
 1096: 
 1097: The value of it is stored in $Apache:lonxml::counter when live and
 1098: stored back to env after done.
 1099: 
 1100: =item &increment_counter($increment);
 1101: 
 1102: Increments the internal counter environment variable a specified amount
 1103: 
 1104: Optional Arguments:
 1105:   $increment - amount to increment by (defaults to 1)
 1106:                Also 1 if the value is negative or zero.
 1107:   $part_response - A concatenation of the part and response id
 1108:                    identifying exactly what is being 'answered'.
 1109: 
 1110: 
 1111: =cut
 1112: 
 1113: sub increment_counter {
 1114:     my ($increment, $part_response) = @_;
 1115:     if ($env{'form.grade_noincrement'}) { return; }
 1116:     if (!defined($increment) || $increment le 0) {
 1117: 	$increment = 1;
 1118:     }
 1119:     $Apache::lonxml::counter += $increment;
 1120: 
 1121:     # If the caller supplied the response_id parameter, 
 1122:     # Maintain its counter.. creating if necessary.
 1123: 
 1124:     if (defined($part_response)) {
 1125: 	if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
 1126: 	    $Apache::lonxml::counters_per_part{$part_response} = 0;
 1127: 	}
 1128: 	$Apache::lonxml::counters_per_part{$part_response} += $increment;
 1129: 	my $new_value = $Apache::lonxml::counters_per_part{$part_response};
 1130:     }
 1131: 	
 1132:     $Apache::lonxml::counter_changed=1;
 1133: }
 1134: 
 1135: =pod
 1136: 
 1137: =item &init_counter($increment);
 1138: 
 1139: Initialize the internal counter environment variable
 1140: 
 1141: =cut
 1142: 
 1143: sub init_counter {
 1144:     if ($env{'request.state'} eq 'construct') {
 1145: 	$Apache::lonxml::counter=1;
 1146: 	$Apache::lonxml::counter_changed=1;
 1147:     } elsif (defined($env{'form.counter'})) {
 1148: 	$Apache::lonxml::counter=$env{'form.counter'};
 1149: 	$Apache::lonxml::counter_changed=0;
 1150:     } else {
 1151: 	$Apache::lonxml::counter=1;
 1152: 	$Apache::lonxml::counter_changed=1;
 1153:     }
 1154: }
 1155: 
 1156: sub store_counter {
 1157:     &Apache::lonnet::appenv({'form.counter' => $Apache::lonxml::counter});
 1158:     $Apache::lonxml::counter_changed=0;
 1159:     return '';
 1160: }
 1161: 
 1162: {
 1163:     my $state;
 1164:     sub clear_problem_counter {
 1165: 	undef($state);
 1166: 	&Apache::lonnet::delenv('form.counter');
 1167: 	&Apache::lonxml::init_counter();
 1168: 	&Apache::lonxml::store_counter();
 1169:     }
 1170: 
 1171:     sub remember_problem_counter {
 1172: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
 1173: 	$state = $env{'form.counter'};
 1174:     }
 1175: 
 1176:     sub restore_problem_counter {
 1177: 	if (defined($state)) {
 1178: 	    &Apache::lonnet::appenv({'form.counter' => $state});
 1179: 	}
 1180:     }
 1181:     sub get_problem_counter {
 1182: 	if ($Apache::lonxml::counter_changed) { &store_counter() }
 1183: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
 1184: 	return $env{'form.counter'};
 1185:     }
 1186: }
 1187: 
 1188: =pod
 1189: 
 1190: =item  bubble_lines_for_part(part_response)
 1191: 
 1192: Returns the number of lines required to get a response for
 1193: $part_response (this is just $Apache::lonxml::counters_per_part{$part_response}
 1194: 
 1195: =cut
 1196: 
 1197: sub bubble_lines_for_part {
 1198:     my ($part_response) = @_;
 1199: 
 1200:     if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
 1201: 	return 0;
 1202:     } else {
 1203: 	return $Apache::lonxml::counters_per_part{$part_response};
 1204:     }
 1205: }
 1206: 
 1207: =pod
 1208: 
 1209: =item clear_bubble_lines_for_part
 1210: 
 1211: Clears the hash of bubble lines per part.  If a caller
 1212: needs to analyze several resources this should be called between
 1213: resources to reset the hash for each problem being analyzed.
 1214: 
 1215: =cut
 1216: 
 1217: sub clear_bubble_lines_for_part {
 1218:     undef(%Apache::lonxml::counters_per_part);
 1219: }
 1220: 
 1221: =pod
 1222: 
 1223: =item set_bubble_lines(part_response, value)
 1224: 
 1225: If there is a problem part, that for whatever reason
 1226: requires bubble lines that are not
 1227: the same as the counter increment, it can call this sub during
 1228: analysis to set its hash value explicitly.
 1229: 
 1230: =cut
 1231: 
 1232: sub set_bubble_lines {
 1233:     my ($part_response, $value) = @_;
 1234: 
 1235:     $Apache::lonxml::counters_per_part{$part_response} = $value;
 1236: }
 1237: 
 1238: =pod
 1239: 
 1240: =item get_bubble_line_hash
 1241: 
 1242: Returns the current bubble line hash.  This is assumed to 
 1243: be small so we return a copy
 1244: 
 1245: 
 1246: =cut
 1247: 
 1248: sub get_bubble_line_hash {
 1249:     return %Apache::lonxml::counters_per_part;
 1250: }
 1251: 
 1252: 
 1253: #--------------------------------------------------
 1254: 
 1255: sub get_all_text {
 1256:     my($tag,$pars,$style)= @_;
 1257:     my $gotfullstack=1;
 1258:     if (ref($pars) ne 'ARRAY') {
 1259: 	$gotfullstack=0;
 1260: 	$pars=[$pars];
 1261:     }
 1262:     if (ref($style) ne 'HASH') {
 1263: 	$style={};
 1264:     }
 1265:     my $depth=0;
 1266:     my $token;
 1267:     my $result='';
 1268:     if ( $tag =~ m:^/: ) { 
 1269: 	my $tag=substr($tag,1); 
 1270: 	#&Apache::lonxml::debug("have:$tag:");
 1271: 	my $top_empty=0;
 1272: 	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
 1273: 	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
 1274: 		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
 1275: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
 1276: 		    if ($token->[2]) {
 1277: 			$result.='<![CDATA['.$token->[1].']]>';
 1278: 		    } else {
 1279: 			$result.=$token->[1];
 1280: 		    }
 1281: 		} elsif ($token->[0] eq 'PI') {
 1282: 		    $result.=$token->[2];
 1283: 		} elsif ($token->[0] eq 'S') {
 1284: 		    if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
 1285: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1286: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1287: 		    $result.=$token->[4];
 1288: 		} elsif ($token->[0] eq 'E')  {
 1289: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
 1290: 		    #skip sending back the last end tag
 1291: 		    if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
 1292: 			my $string=
 1293: 			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
 1294: 				$$style{'/'.$token->[1]}.
 1295: 				    $token->[2].
 1296: 					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
 1297: 			&Apache::lonxml::newparser($pars,\$string);
 1298: 			#&Apache::lonxml::debug("reParsing $string");
 1299: 			next;
 1300: 		    }
 1301: 		    if ($depth > -1) {
 1302: 			$result.=$token->[2];
 1303: 		    } else {
 1304: 			$$pars[-1]->unget_token($token);
 1305: 		    }
 1306: 		}
 1307: 	    }
 1308: 	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
 1309: 	    if (($depth >=0) && ($#$pars > 0) ) {
 1310: 		pop(@$pars);
 1311: 		pop(@Apache::lonxml::pwd);
 1312: 	    }
 1313: 	}
 1314: 	if ($top_empty && $depth >= 0) {
 1315: 	    #never found the end tag ran out of text, throw error send back blank
 1316: 	    &error('Never found end tag for &lt;'.$tag.
 1317: 		   '&gt; current string <pre>'.
 1318: 		   &HTML::Entities::encode($result,'<>&"').
 1319: 		   '</pre>');
 1320: 	    if ($gotfullstack) {
 1321: 		my $newstring='</'.$tag.'>'.$result;
 1322: 		&Apache::lonxml::newparser($pars,\$newstring);
 1323: 	    }
 1324: 	    $result='';
 1325: 	}
 1326:     } else {
 1327: 	while ($#$pars > -1) {
 1328: 	    while ($token = $$pars[-1]->get_token) {
 1329: 		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
 1330: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
 1331: 		    ($token->[0] eq 'D')) {
 1332: 		    if ($token->[2]) {
 1333: 			$result.='<![CDATA['.$token->[1].']]>';
 1334: 		    } else {
 1335: 			$result.=$token->[1];
 1336: 		    }
 1337: 		} elsif ($token->[0] eq 'PI') {
 1338: 		    $result.=$token->[2];
 1339: 		} elsif ($token->[0] eq 'S') {
 1340: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) {
 1341: 			$$pars[-1]->unget_token($token); last;
 1342: 		    } else {
 1343: 			$result.=$token->[4];
 1344: 		    }
 1345: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
 1346: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
 1347: 		} elsif ($token->[0] eq 'E')  {
 1348: 		    $result.=$token->[2];
 1349: 		}
 1350: 	    }
 1351: 	    if (($#$pars > 0) ) {
 1352: 		pop(@$pars);
 1353: 		pop(@Apache::lonxml::pwd);
 1354: 	    } else { last; }
 1355: 	}
 1356:     }
 1357:     #&Apache::lonxml::debug("Exit:$result:");
 1358:     return $result
 1359: }
 1360: 
 1361: sub newparser {
 1362:   my ($parser,$contentref,$dir) = @_;
 1363:   push (@$parser,HTML::LCParser->new($contentref));
 1364:   $$parser[-1]->xml_mode(1);
 1365:   $$parser[-1]->marked_sections(1);
 1366:   if ( $dir eq '' ) {
 1367:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
 1368:   } else {
 1369:     push (@Apache::lonxml::pwd, $dir);
 1370:   } 
 1371: }
 1372: 
 1373: sub parstring {
 1374:     my ($token) = @_;
 1375:     my (@vars,@values);
 1376:     foreach my $attr (@{$token->[3]}) {
 1377: 	if ($attr!~/\W/) {
 1378: 	    my $val=$token->[2]->{$attr};
 1379: 	    $val =~ s/([\%\@\\\"\'])/\\$1/g;
 1380: 	    $val =~ s/(\$[^\{a-zA-Z_])/\\$1/g;
 1381: 	    $val =~ s/(\$)$/\\$1/;
 1382: 	    #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
 1383: 	    push(@vars,"\$$attr");
 1384: 	    push(@values,"\"$val\"");
 1385: 	}
 1386:     }
 1387:     my $var_init = 
 1388: 	(@vars) ? 'my ('.join(',',@vars).') = ('.join(',',@values).');'
 1389: 	        : '';
 1390:     return $var_init;
 1391: }
 1392: 
 1393: sub extlink {
 1394:     my ($res,$exact)=@_;
 1395:     if (!$exact) {
 1396: 	$res=&Apache::lonnet::hreflocation($Apache::lonxml::pwd[-1],$res);
 1397:     }
 1398:     push(@Apache::lonxml::extlinks,$res)	 
 1399: }
 1400: 
 1401: sub writeallows {
 1402:     unless ($#extlinks>=0) { return; }
 1403:     my $thisurl = &Apache::lonnet::clutter(shift);
 1404:     if ($env{'httpref.'.$thisurl}) {
 1405: 	$thisurl=$env{'httpref.'.$thisurl};
 1406:     }
 1407:     my $thisdir=$thisurl;
 1408:     $thisdir=~s/\/[^\/]+$//;
 1409:     my %httpref=();
 1410:     foreach (@extlinks) {
 1411:        $httpref{'httpref.'.
 1412:  	        &Apache::lonnet::hreflocation($thisdir,&unescape($_))}=$thisurl;
 1413:     }
 1414:     @extlinks=();
 1415:     &Apache::lonnet::appenv(\%httpref);
 1416: }
 1417: 
 1418: sub register_ssi {
 1419:     my ($url,%form)=@_;
 1420:     push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
 1421:     return '';
 1422: }
 1423: 
 1424: sub do_registered_ssi {
 1425:     foreach my $info (@Apache::lonxml::ssi_info) {
 1426: 	my %form=%{ $info->{'form'}};
 1427: 	my $url=$info->{'url'};
 1428: 	&Apache::lonnet::ssi($url,%form);
 1429:     }
 1430: }
 1431: 
 1432: sub add_script_result {
 1433:     my ($display) = @_;
 1434:     push(@script_var_displays, $display);
 1435: }
 1436: 
 1437: #
 1438: # Afterburner handles anchors, highlights and links
 1439: #
 1440: sub afterburn {
 1441:     my $result=shift;
 1442:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1443: 					    ['highlight','anchor','link']);
 1444:     if ($env{'form.highlight'}) {
 1445:        foreach (split(/\,/,$env{'form.highlight'})) {
 1446:            my $anchorname=$_;
 1447: 	   my $matchthis=$anchorname;
 1448:            $matchthis=~s/\_+/\\s\+/g;
 1449:            $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1450:        }
 1451:     }
 1452:     if ($env{'form.link'}) {
 1453:        foreach (split(/\,/,$env{'form.link'})) {
 1454:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1455: 	   my $matchthis=$anchorname;
 1456:            $matchthis=~s/\_+/\\s\+/g;
 1457:            $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1458:        }
 1459:     }
 1460:     if ($env{'form.anchor'}) {
 1461:         my $anchorname=$env{'form.anchor'};
 1462: 	my $matchthis=$anchorname;
 1463:         $matchthis=~s/\_+/\\s\+/g;
 1464:         $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1465:         $result.=(<<"ENDSCRIPT");
 1466: <script type="text/javascript">
 1467:     document.location.hash='$anchorname';
 1468: </script>
 1469: ENDSCRIPT
 1470:     }
 1471:     return $result;
 1472: }
 1473: 
 1474: sub storefile {
 1475:     my ($file,$contents)=@_;
 1476:     &Apache::lonnet::correct_line_ends(\$contents);
 1477:     if (my $fh=Apache::File->new('>'.$file)) {
 1478: 	print $fh $contents;
 1479:         $fh->close();
 1480:         return 1;
 1481:     } else {
 1482: 	&warning(&mt('Unable to save file [_1]','<tt>'.$file.'</tt>'));
 1483: 	return 0;
 1484:     }
 1485: }
 1486: 
 1487: sub createnewhtml {
 1488:     my $title=&mt('Title of document goes here');
 1489:     my $body=&mt('Body of document goes here');
 1490:     my $filecontents=(<<SIMPLECONTENT);
 1491: <html>
 1492: <head>
 1493: <title>$title</title>
 1494: </head>
 1495: <body bgcolor="#FFFFFF">
 1496: $body
 1497: </body>
 1498: </html>
 1499: SIMPLECONTENT
 1500:     return $filecontents;
 1501: }
 1502: 
 1503: sub createnewsty {
 1504:   my $filecontents=(<<SIMPLECONTENT);
 1505: <definetag name="">
 1506:     <render>
 1507:        <web></web>
 1508:        <tex></tex>
 1509:     </render>
 1510: </definetag>
 1511: SIMPLECONTENT
 1512:   return $filecontents;
 1513: }
 1514: 
 1515: sub createnewjs {
 1516:     my $filecontents=(<<SIMPLECONTENT);
 1517: <script type="text/javascript" language="Javascript">
 1518: 
 1519: </script>
 1520: SIMPLECONTENT
 1521:     return $filecontents;
 1522: }
 1523: 
 1524: sub verify_html {
 1525:     my ($filecontents)=@_;
 1526:     if ($filecontents!~/(?:\<|\&lt\;)(?:html|xml)[^\<]*(?:\>|\&gt\;)/is) {
 1527:        return &mt('File does not have [_1] or [_2] starting tag','&lt;html&gt;','&lt;xml&gt;');
 1528:     }
 1529:     if ($filecontents!~/(?:\<|\&lt\;)\/(?:html|xml)(?:\>|\&gt\;)/is) {
 1530:        return &mt('File does not have [_1] or [_2] ending tag','&lt;html&gt;','&lt;xml&gt;');
 1531:     }
 1532:     if ($filecontents!~/(?:\<|\&lt\;)(?:body|frameset)[^\<]*(?:\>|\&gt\;)/is) {
 1533:        return &mt('File does not have [_1] or [_2] starting tag','&lt;body&gt;','&lt;frameset&gt;');
 1534:     }
 1535:     if ($filecontents!~/(?:\<|\&lt\;)\/(?:body|frameset)[^\<]*(?:\>|\&gt\;)/is) {
 1536:        return &mt('File does not have [_1] or [_2] ending tag','&lt;body&gt;','&lt;frameset&gt;');
 1537:     }
 1538:     return '';
 1539: }
 1540: 
 1541: sub renderingoptions {
 1542:     my %langchoices=('' => '');
 1543:     foreach (&Apache::loncommon::languageids()) {
 1544:         if (&Apache::loncommon::supportedlanguagecode($_)) {
 1545:             $langchoices{&Apache::loncommon::supportedlanguagecode($_)}
 1546:                        = &Apache::loncommon::plainlanguagedescription($_);
 1547:         }
 1548:     }
 1549:     return
 1550:        '<span class="LC_nobreak">'.
 1551:        &mt('Language:').' '.
 1552:        &Apache::loncommon::select_form($env{'form.languages'},'languages',
 1553:                                                      %langchoices).'
 1554:      </span>
 1555:      <span class="LC_nobreak">'.
 1556:        &mt('Math Rendering:').' '.
 1557:        &Apache::loncommon::select_form($env{'form.texengine'},'texengine',
 1558:                                                      ('' => '',
 1559:                                                       'tth' => 'tth (TeX to HTML)',
 1560:                                                       'jsMath' => 'jsMath',
 1561:                                                       'mimetex' => 'mimetex (Convert to Images)')).'
 1562:      </span>';
 1563: }
 1564: 
 1565: sub inserteditinfo {
 1566:       my ($filecontents, $filetype, $filename)=@_;
 1567:       $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
 1568:       my $xml_help = '';
 1569:       my $initialize='';
 1570:       my $textarea_id = 'filecont';
 1571:       my $dragmath_button;
 1572:       my ($add_to_onload, $add_to_onresize);
 1573:       $initialize=&Apache::lonhtmlcommon::spellheader();
 1574:       if ($filetype eq 'html' 
 1575: 	  && (!&Apache::lonhtmlcommon::htmlareablocked() &&
 1576: 	      &Apache::lonhtmlcommon::htmlareabrowser())) {
 1577: 	  $textarea_id .= '___Frame';
 1578: 	  my $lang = &Apache::lonhtmlcommon::htmlarea_lang();
 1579: 	  $initialize.=(<<FULLPAGE);
 1580: <script type="text/javascript">
 1581: lonca
 1582:     function initDocument() {
 1583:         var oFCKeditor = new FCKeditor('filecont');
 1584: 	oFCKeditor.Config['CustomConfigurationsPath'] = '/fckeditor/loncapaconfig.js'  ;
 1585: 	oFCKeditor.Config['FullPage'] = true
 1586: 	oFCKeditor.Config['AutoDetectLanguage'] = false;
 1587:         oFCKeditor.Config['DefaultLanguage'] = "$lang";
 1588: 	oFCKeditor.ReplaceTextarea();
 1589:     }
 1590:     function check_if_dirty(editor) {
 1591: 	if (editor.IsDirty()) {
 1592: 	    unClean();
 1593: 	}
 1594:     }
 1595:     function FCKeditor_OnComplete(editor) {
 1596: 	editor.Events.AttachEvent("OnSelectionChange",check_if_dirty);
 1597: 	resize_textarea('$textarea_id','LC_aftertextarea');
 1598:     }
 1599: </script>
 1600: FULLPAGE
 1601:       } else {
 1602: 	  $initialize.=(<<FULLPAGE);
 1603: <script type="text/javascript">
 1604:     function initDocument() {
 1605: 	resize_textarea('$textarea_id','LC_aftertextarea');
 1606:     }
 1607: </script>
 1608: FULLPAGE
 1609:           if ($filetype eq 'html') {
 1610:               $initialize .= "\n".&Apache::lonhtmlcommon::dragmath_js('EditMathPopup');
 1611:               $dragmath_button = &Apache::lonhtmlcommon::dragmath_button('filecont',1);
 1612:           }
 1613:       }
 1614: 
 1615:       $add_to_onload = 'initDocument();';
 1616:       $add_to_onresize = "resize_textarea('$textarea_id','LC_aftertextarea');";
 1617: 
 1618:       if ($filetype eq 'html') {
 1619: 	  $xml_help=&Apache::loncommon::helpLatexCheatsheet();
 1620:       }
 1621: 
 1622:       my $titledisplay=&display_title();
 1623:       my %lt=&Apache::lonlocal::texthash('st' => 'Save and Edit',
 1624: 					 'vi' => 'Save and View',
 1625: 					 'dv' => 'Discard Edits and View',
 1626: 					 'un' => 'undo',
 1627: 					 'ed' => 'Edit');
 1628:       my $spelllink .=&Apache::lonhtmlcommon::spelllink('xmledit','filecont');
 1629:       my $textarea_events = &Apache::edit::element_change_detection();
 1630:       my $form_events     = &Apache::edit::form_change_detection();
 1631:       my $htmlerror;
 1632:       if ($filetype eq 'html') {
 1633:           $htmlerror=&verify_html($filecontents);
 1634:           if ($htmlerror) {
 1635:               $htmlerror='<span class="LC_error">'.$htmlerror.'</span>';
 1636:           }
 1637:       }
 1638:       my $editfooter=(<<ENDFOOTER);
 1639: $initialize
 1640: <a name="editsection" />
 1641: <form $form_events method="post" name="xmledit">
 1642:   <div class="LC_edit_problem_editxml_header">
 1643:     <table class="LC_edit_problem_header_title"><tr><td>
 1644:         $filename
 1645:       </td><td align="right">
 1646:         $xml_help
 1647:       </td></tr>
 1648:     </table>
 1649:     <div class="LC_edit_problem_discards">
 1650:       <input type="submit" name="discardview" accesskey="d" value="$lt{'dv'}" />
 1651:       <input type="submit" name="Undo" accesskey="u" value="$lt{'un'}" />
 1652:       $dragmath_button $spelllink $htmlerror
 1653:     </div>
 1654:     <div class="LC_edit_problem_saves">
 1655:       <input type="submit" name="savethisfile" accesskey="s" value="$lt{'st'}" />
 1656:       <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
 1657:     </div>
 1658:   </div>
 1659:   <textarea $textarea_events style="width:100%" cols="80" rows="44" name="filecont" id="filecont">$filecontents</textarea>
 1660:   <div id="LC_aftertextarea">
 1661:     <br />
 1662:     $titledisplay
 1663:   </div>
 1664: </form>
 1665: </body>
 1666: ENDFOOTER
 1667:       return ($editfooter,$add_to_onload,$add_to_onresize);;
 1668: }
 1669: 
 1670: sub get_target {
 1671:   my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
 1672:   if ( $env{'request.state'} eq 'published') {
 1673:     if ( defined($env{'form.grade_target'})
 1674: 	 && ($viewgrades == 'F' )) {
 1675:       return ($env{'form.grade_target'});
 1676:     } elsif (defined($env{'form.grade_target'})) {
 1677:       if (($env{'form.grade_target'} eq 'web') ||
 1678: 	  ($env{'form.grade_target'} eq 'tex') ) {
 1679: 	return $env{'form.grade_target'}
 1680:       } else {
 1681: 	return 'web';
 1682:       }
 1683:     } else {
 1684:       return 'web';
 1685:     }
 1686:   } elsif ($env{'request.state'} eq 'construct') {
 1687:     if ( defined($env{'form.grade_target'})) {
 1688:       return ($env{'form.grade_target'});
 1689:     } else {
 1690:       return 'web';
 1691:     }
 1692:   } else {
 1693:     return 'web';
 1694:   }
 1695: }
 1696: 
 1697: sub handler {
 1698:     my $request=shift;
 1699: 
 1700:     my $target=&get_target();
 1701:     $Apache::lonxml::debug=$env{'user.debug'};
 1702:     
 1703:     &Apache::loncommon::content_type($request,'text/html');
 1704:     &Apache::loncommon::no_cache($request);
 1705:     if ($env{'request.state'} eq 'published') {
 1706: 	$request->set_last_modified(&Apache::lonnet::metadata($request->uri,
 1707: 							      'lastrevisiondate'));
 1708:     }
 1709:     # Embedded Flash movies (e.g., from Camtasia) served from https will not display in IE
 1710:     #   if XML config file has expired from cache.
 1711:     if ($ENV{'SERVER_PORT'} == 443) {
 1712:         if ($request->uri =~ /\.xml$/) {
 1713:             my ($httpbrowser,$clientbrowser) =
 1714:                 &Apache::loncommon::decode_user_agent($request);
 1715:             if ($clientbrowser =~ /^explorer$/i) {
 1716:                 delete $request->headers_out->{'Cache-control'};
 1717:                 delete $request->headers_out->{'Pragma'};
 1718:                 my $expiration = time + 60;
 1719:                 my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime($expiration));
 1720:                 $request->headers_out->set("Expires" => $date);
 1721:             }
 1722:         }
 1723:     }
 1724:     $request->send_http_header;
 1725:     
 1726:     return OK if $request->header_only;
 1727: 
 1728: 
 1729:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1730:     my $filetype;
 1731:     if ($file =~ /\.(sty|css|js|txt)$/) {
 1732: 	$filetype=$1;
 1733:     } else {
 1734: 	$filetype='html';
 1735:     }
 1736: 
 1737: #
 1738: # Edit action? Save file.
 1739: #
 1740:     if (!($env{'request.state'} eq 'published')) {
 1741: 	if ($env{'form.savethisfile'} || $env{'form.viewmode'} || $env{'form.Undo'}) {
 1742: 	    my $html_file=&Apache::lonnet::getfile($file);
 1743: 	    my $error = &Apache::lonhomework::handle_save_or_undo($request, \$html_file, \$env{'form.filecont'});
 1744:             if ($env{'form.savethisfile'}) {
 1745:                 $env{'form.editmode'}='Edit'; #force edit mode
 1746:             }
 1747: 	}
 1748:     }
 1749:     my %mystyle;
 1750:     my $result = '';
 1751:     my $filecontents=&Apache::lonnet::getfile($file);
 1752:     if ($filecontents eq -1) {
 1753: 	my $start_page=&Apache::loncommon::start_page('File Error');
 1754: 	my $end_page=&Apache::loncommon::end_page();
 1755: 	my $fnf=&mt('File not found');
 1756: 	$result=(<<ENDNOTFOUND);
 1757: $start_page
 1758: <b>$fnf: $file</b>
 1759: $end_page
 1760: ENDNOTFOUND
 1761:         $filecontents='';
 1762: 	if ($env{'request.state'} ne 'published') {
 1763: 	    if ($filetype eq 'sty') {
 1764: 		$filecontents=&createnewsty();
 1765:             } elsif ($filetype eq 'js') {
 1766:                 $filecontents=&createnewjs();
 1767:             } elsif (($filetype ne 'css') && ($filetype ne 'txt')) {
 1768: 		$filecontents=&createnewhtml();
 1769: 	    }
 1770: 	    $env{'form.editmode'}='Edit'; #force edit mode
 1771: 	}
 1772:     } else {
 1773: 	unless ($env{'request.state'} eq 'published') {
 1774: 	    if ($filecontents=~/BEGIN LON-CAPA Internal/) {
 1775: 		&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.'));
 1776: 	    }
 1777: #
 1778: # we are in construction space, see if edit mode forced
 1779:             &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1780: 						    ['editmode']);
 1781: 	}
 1782: 	if (!$env{'form.editmode'} || $env{'form.viewmode'} || $env{'form.discardview'}) {
 1783:             if ($filetype eq 'html' || $filetype eq 'sty') {
 1784: 	        &Apache::structuretags::reset_problem_globals();
 1785: 	        $result = &Apache::lonxml::xmlparse($request,$target,
 1786:                                                     $filecontents,'',%mystyle);
 1787: 	    # .html files may contain <problem> or <Task> need to clean
 1788: 	    # up if it did
 1789: 	        &Apache::structuretags::reset_problem_globals();
 1790: 	        &Apache::lonhomework::finished_parsing();
 1791:             } else {
 1792:                 $result = $filecontents;
 1793:             }
 1794: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1795: 						    ['rawmode']);
 1796: 	    if ($env{'form.rawmode'}) { $result = $filecontents; }
 1797: 	    if ($filetype ne 'html') {
 1798:                 my $nochgview = 1; 
 1799: 		my $controls =
 1800: 		    ($env{'request.state'} eq 'construct') ? &Apache::londefdef::edit_controls($nochgview)
 1801: 		                                           : '';
 1802:                 if ($filetype ne 'sty') {
 1803:                     $result =~ s/</&lt;/g;
 1804:                     $result =~ s/>/&gt;/g;
 1805:                     $result = '<table class="LC_sty_begin">'.
 1806:                               '<tr><td><b><pre>'.$result.
 1807:                               '</pre></b></td></tr></table>';
 1808:                 }
 1809:                 if ($env{'environment.remote'} eq 'off') {
 1810:                     my %options = ('bgcolor' => '#FFFFFF');
 1811: 		    $result = 
 1812: 		        &Apache::loncommon::start_page(undef,undef,\%options).
 1813: 		        $controls.
 1814: 		        $result.
 1815: 		        &Apache::loncommon::end_page();
 1816:                 } else {
 1817:                     $result = $controls.$result;
 1818:                 }
 1819:             }
 1820: 	}
 1821:     }
 1822: 
 1823: #
 1824: # Edit action? Insert editing commands
 1825: #
 1826:     unless ($env{'request.state'} eq 'published') {
 1827: 	if ($env{'form.editmode'} && (!($env{'form.viewmode'})) && (!($env{'form.discardview'})))
 1828: 	{
 1829: 	    my $displayfile=$request->uri;
 1830: 	    $displayfile=~s/^\/[^\/]*//;
 1831: 
 1832: 	    my ($edit_info, $add_to_onload, $add_to_onresize)=
 1833: 		&inserteditinfo($filecontents,$filetype,$displayfile);
 1834: 
 1835: 	    my %options = 
 1836: 		('add_entries' =>
 1837:                    {'onresize' => $add_to_onresize,
 1838: 		    'onload'   => $add_to_onload,   });
 1839: 
 1840: 	    if ($env{'environment.remote'} ne 'off') {
 1841: 		$options{'bgcolor'}   = '#FFFFFF';
 1842: 		$options{'only_body'} = 1;
 1843: 	    }
 1844: 	    my $js =
 1845: 		&Apache::edit::js_change_detection().
 1846: 		&Apache::loncommon::resize_textarea_js();
 1847: 	    my $start_page = &Apache::loncommon::start_page(undef,$js,
 1848: 							    \%options);
 1849: 	    $result=$start_page.
 1850: 		&Apache::lonxml::message_location().
 1851: 		$edit_info.
 1852: 		&Apache::loncommon::end_page();
 1853:         }
 1854:     }
 1855:     if ($filetype eq 'html') { &writeallows($request->uri); }
 1856:     
 1857:     &Apache::lonxml::add_messages(\$result);
 1858:     $request->print($result);
 1859:     
 1860:     return OK;
 1861: }
 1862: 
 1863: sub display_title {
 1864:     my $result;
 1865:     if ($env{'request.state'} eq 'construct') {
 1866: 	my $title=&Apache::lonnet::gettitle();
 1867: 	if (!defined($title) || $title eq '') {
 1868: 	    $title = $env{'request.filename'};
 1869: 	    $title = substr($title, rindex($title, '/') + 1);
 1870: 	}
 1871:         $result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA "
 1872:                   .&mt('Construction Space')."';</script>";
 1873:     }
 1874:     return $result;
 1875: }
 1876: 
 1877: sub debug {
 1878:     if ($Apache::lonxml::debug eq "1") {
 1879: 	$|=1;
 1880: 	my $request=$Apache::lonxml::request;
 1881: 	if (!$request) {
 1882: 	    eval { $request=Apache->request; };
 1883: 	}
 1884: 	if (!$request) {
 1885: 	    eval { $request=Apache2::RequestUtil->request; };
 1886: 	}
 1887: 	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
 1888: 	#&Apache::lonnet::logthis($_[0]);
 1889:     }
 1890: }
 1891: 
 1892: sub show_error_warn_msg {
 1893:     if ($env{'request.filename'} eq '/home/httpd/html/res/lib/templates/simpleproblem.problem' &&
 1894: 	&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
 1895: 	return 1;
 1896:     }
 1897:     return (($Apache::lonxml::debug eq 1) ||
 1898: 	    ($env{'request.state'} eq 'construct') ||
 1899: 	    ($Apache::lonhomework::browse eq 'F'
 1900: 	     &&
 1901: 	     $env{'form.show_errors'} eq 'on'));
 1902: }
 1903: 
 1904: sub error {
 1905:     my @errors = @_;
 1906: 
 1907:     $errorcount++;
 1908: 
 1909:     $Apache::lonxml::internal_error=1;
 1910: 
 1911:     if (defined($Apache::inputtags::part)) {
 1912: 	if ( @Apache::inputtags::response ) {
 1913: 	    push(@errors,
 1914: 		 &mt("This error occurred while processing response [_1] in part [_2]",
 1915: 		     $Apache::inputtags::response[-1],
 1916: 		     $Apache::inputtags::part));
 1917: 	} else {
 1918: 	    push(@errors,
 1919: 		 &mt("This error occurred while processing part [_1]",
 1920: 		     $Apache::inputtags::part));
 1921: 	}
 1922:     }
 1923: 
 1924:     if ( &show_error_warn_msg() ) {
 1925: 	# If printing in construction space, put the error inside <pre></pre>
 1926: 	push(@Apache::lonxml::error_messages,
 1927: 	     $Apache::lonxml::warnings_error_header
 1928:              .'<div class="LC_error">'
 1929:              .'<b>'.&mt('ERROR:').' </b>'.join("<br />\n",@errors)
 1930:              ."</div>\n");
 1931: 	$Apache::lonxml::warnings_error_header='';
 1932:     } else {
 1933: 	my $errormsg;
 1934: 	my ($symb)=&Apache::lonnet::symbread();
 1935: 	if ( !$symb ) {
 1936: 	    #public or browsers
 1937: 	    $errormsg=&mt("An error occurred while processing this resource. The author has been notified.");
 1938: 	}
 1939: 	my $host=$Apache::lonnet::perlvar{'lonHostID'};
 1940: 	push(@errors,
 1941:         &mt("The error occurred on host [_1]",
 1942:              "<tt>$host</tt>"));
 1943: 
 1944: 	my $msg = join('<br />', @errors);
 1945: 
 1946: 	#notify author
 1947: 	&Apache::lonmsg::author_res_msg($env{'request.filename'},$msg);
 1948: 	#notify course
 1949: 	if ( $symb && $env{'request.course.id'} ) {
 1950: 	    my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1951: 	    my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1952: 	    my (undef,%users)=&Apache::lonmsg::decide_receiver(undef,0,1,1,1);
 1953: 	    my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
 1954:             my $baseurl = &Apache::lonnet::clutter($declutter);
 1955: 	    my @userlist;
 1956: 	    foreach (keys %users) {
 1957: 		my ($user,$domain) = split(/:/, $_);
 1958: 		push(@userlist,"$user\@$domain");
 1959: 		my $key=$declutter.'_'.$user.'_'.$domain;
 1960: 		my %lastnotified=&Apache::lonnet::get('nohist_xmlerrornotifications',
 1961: 						      [$key],
 1962: 						      $cdom,$cnum);
 1963: 		my $now=time;
 1964: 		if ($now-$lastnotified{$key}>86400) {
 1965:                     my $title = &Apache::lonnet::gettitle($symb);
 1966:                     my $sentmessage;
 1967: 		    &Apache::lonmsg::user_normal_msg($user,$domain,
 1968: 		        "Error [$title]",$msg,'',$baseurl,'','',
 1969:                         \$sentmessage,$symb,$title,1);
 1970: 		    &Apache::lonnet::put('nohist_xmlerrornotifications',
 1971: 					 {$key => $now},
 1972: 					 $cdom,$cnum);		
 1973: 		}
 1974: 	    }
 1975: 	    if ($env{'request.role.adv'}) {
 1976: 		$errormsg=&mt("An error occurred while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
 1977: 	    } else {
 1978: 		$errormsg=&mt("An error occurred while processing this resource. The instructor has been notified.");
 1979: 	    }
 1980: 	}
 1981: 	push(@Apache::lonxml::error_messages,"<b>$errormsg</b> <br />");
 1982:     }
 1983: }
 1984: 
 1985: sub warning {
 1986:     $warningcount++;
 1987:   
 1988:     if ($env{'form.grade_target'} ne 'tex') {
 1989: 	if ( &show_error_warn_msg() ) {
 1990: 	    push(@Apache::lonxml::warning_messages,
 1991: 		 $Apache::lonxml::warnings_error_header
 1992:                 .'<div class="LC_warning">'
 1993:                 .&mt('[_1]W[_2]ARNING','<b>','</b>')."<b>:</b> ".join('<br />',@_)
 1994:                 ."</div>\n"
 1995:                 );
 1996: 	    $Apache::lonxml::warnings_error_header='';
 1997: 	}
 1998:     }
 1999: }
 2000: 
 2001: sub info {
 2002:     if ($env{'form.grade_target'} ne 'tex' 
 2003: 	&& $env{'request.state'} eq 'construct') {
 2004: 	push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
 2005:     }
 2006: }
 2007: 
 2008: sub message_location {
 2009:     return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
 2010: }
 2011: 
 2012: sub add_messages {
 2013:     my ($msg)=@_;
 2014:     my $result=join(' ',
 2015: 		    @Apache::lonxml::info_messages,
 2016: 		    @Apache::lonxml::error_messages,
 2017: 		    @Apache::lonxml::warning_messages);
 2018:     undef(@Apache::lonxml::info_messages);
 2019:     undef(@Apache::lonxml::error_messages);
 2020:     undef(@Apache::lonxml::warning_messages);
 2021:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
 2022:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
 2023: }
 2024: 
 2025: sub get_param {
 2026:     my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 2027:     if ( ! $context ) { $context = -1; }
 2028:     my $args ='';
 2029:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 2030:     if ( ! $Apache::lonxml::usestyle ) {
 2031: 	$args=$Apache::lonxml::style_values.$args;
 2032:     }
 2033:     if ( ! $args ) { return undef; }
 2034:     if ( $case_insensitive ) {
 2035: 	if ($args =~ s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei) {
 2036: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 2037:                                      $safeeval); #'
 2038: 	} else {
 2039: 	    return undef;
 2040: 	}
 2041:     } else {
 2042: 	if ( $args =~ /my .*\$\Q$param\E[,\)]/ ) {
 2043: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 2044:                                      $safeeval); #'
 2045: 	} else {
 2046: 	    return undef;
 2047: 	}
 2048:     }
 2049: }
 2050: 
 2051: sub get_param_var {
 2052:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 2053:   if ( ! $context ) { $context = -1; }
 2054:   my $args ='';
 2055:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 2056:   if ( ! $Apache::lonxml::usestyle ) {
 2057:       $args=$Apache::lonxml::style_values.$args;
 2058:   }
 2059:   &Apache::lonxml::debug("Args are $args param is $param");
 2060:   if ($case_insensitive) {
 2061:       if (! ($args=~s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei)) {
 2062: 	  return undef;
 2063:       }
 2064:   } elsif ( $args !~ /my .*\$\Q$param\E[,\)]/ ) { return undef; }
 2065:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 2066:   &Apache::lonxml::debug("first run is $value");
 2067:   if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
 2068:       &Apache::lonxml::debug("doing second");
 2069:       my @result=&Apache::run::run("return $value",$safeeval,1);
 2070:       if (!defined($result[0])) {
 2071: 	  return $value
 2072:       } else {
 2073: 	  if (wantarray) { return @result; } else { return $result[0]; }
 2074:       }
 2075:   } else {
 2076:     return $value;
 2077:   }
 2078: }
 2079: 
 2080: sub register_insert_xml {
 2081:     my $parser = HTML::LCParser->new($Apache::lonnet::perlvar{'lonTabDir'}
 2082: 				     .'/insertlist.xml');
 2083:     my ($tagnum,$in_help)=(0,0);
 2084:     my @alltags;
 2085:     my $tag;
 2086:     while (my $token = $parser->get_token()) {
 2087: 	if ($token->[0] eq 'S') {
 2088: 	    my $key;
 2089: 	    if      ($token->[1] eq 'tag') {
 2090: 		$tag = $token->[2]{'name'};
 2091: 		$insertlist{"$tagnum.tag"} = $tag;
 2092: 		$insertlist{"$tag.num"}   = $tagnum;
 2093: 		push(@alltags,$tag);
 2094: 	    } elsif ($in_help && $token->[1] eq 'file') {
 2095: 		$key = $tag.'.helpfile';
 2096: 	    } elsif ($in_help && $token->[1] eq 'description') {
 2097: 		$key = $tag.'.helpdesc';
 2098: 	    } elsif ($token->[1] eq 'description' ||
 2099: 		     $token->[1] eq 'color'       ||
 2100: 		     $token->[1] eq 'show'          ) {
 2101: 		$key = $tag.'.'.$token->[1];
 2102: 	    } elsif ($token->[1] eq 'insert_sub') {
 2103: 		$key = $tag.'.function';
 2104: 	    } elsif ($token->[1] eq 'help') {
 2105: 		$in_help=1;
 2106: 	    } elsif ($token->[1] eq 'allow') {
 2107: 		$key = $tag.'.allow';
 2108: 	    }
 2109: 	    if (defined($key)) {
 2110: 		$insertlist{$key} = $parser->get_text();
 2111: 		$insertlist{$key} =~ s/(^\s*|\s*$ )//gx;
 2112: 	    }
 2113: 	} elsif ($token->[0] eq 'E') {
 2114: 	    if      ($token->[1] eq 'tag') {
 2115: 		undef($tag);
 2116: 		$tagnum++;
 2117: 	    } elsif ($token->[1] eq 'help') {
 2118: 		undef($in_help);
 2119: 	    }
 2120: 	}
 2121:     }
 2122:     
 2123:     # parse the allows and ignore tags set to <show>no</show>
 2124:     foreach my $tag (@alltags) {	
 2125:         next if (!exists($insertlist{"$tag.allow"}));
 2126: 	my $allow =  $insertlist{"$tag.allow"};
 2127:        	foreach my $element (split(',',$allow)) {
 2128: 	    $element =~ s/(^\s*|\s*$ )//gx;
 2129: 	    if (!exists($insertlist{"$element.show"})
 2130:                 || $insertlist{"$element.show"} ne 'no') {
 2131: 		push(@{ $insertlist{$tag.'.which'} },$element);
 2132: 	    }
 2133: 	}
 2134:     }
 2135: }
 2136: 
 2137: sub register_insert {
 2138:     return &register_insert_xml(@_);
 2139: #    &dump_insertlist('2');
 2140: }
 2141: 
 2142: sub dump_insertlist {
 2143:     my ($ext) = @_;
 2144:     open(XML,">/tmp/insertlist.xml.$ext");
 2145:     print XML ("<insertlist>");
 2146:     my $i=0;
 2147: 
 2148:     while (exists($insertlist{"$i.tag"})) {
 2149: 	my $tag = $insertlist{"$i.tag"};
 2150: 	print XML ("
 2151: \t<tag name=\"$tag\">");
 2152: 	if (defined($insertlist{"$tag.description"})) {
 2153: 	    print XML ("
 2154: \t\t<description>".$insertlist{"$tag.description"}."</description>");
 2155: 	}
 2156: 	if (defined($insertlist{"$tag.color"})) {
 2157: 	    print XML ("
 2158: \t\t<color>".$insertlist{"$tag.color"}."</color>");
 2159: 	}
 2160: 	if (defined($insertlist{"$tag.function"})) {
 2161: 	    print XML ("
 2162: \t\t<insert_sub>".$insertlist{"$tag.function"}."</insert_sub>");
 2163: 	}
 2164: 	if (defined($insertlist{"$tag.show"})
 2165: 	    && $insertlist{"$tag.show"} ne 'yes') {
 2166: 	    print XML ("
 2167: \t\t<show>".$insertlist{"$tag.show"}."</show>");
 2168: 	}
 2169: 	if (defined($insertlist{"$tag.helpfile"})) {
 2170: 	    print XML ("
 2171: \t\t<help>
 2172: \t\t\t<file>".$insertlist{"$tag.helpfile"}."</file>");
 2173: 	    if ($insertlist{"$tag.helpdesc"} ne '') {
 2174: 		print XML ("
 2175: \t\t\t<description>".$insertlist{"$tag.helpdesc"}."</description>");
 2176: 	    }
 2177: 	    print XML ("
 2178: \t\t</help>");
 2179: 	}
 2180: 	if (defined($insertlist{"$tag.which"})) {
 2181: 	    print XML ("
 2182: \t\t<allow>".join(',',sort(@{ $insertlist{"$tag.which"} }))."</allow>");
 2183: 	}
 2184: 	print XML ("
 2185: \t</tag>");
 2186: 	$i++;
 2187:     }
 2188:     print XML ("\n</insertlist>\n");
 2189:     close(XML);
 2190: }
 2191: 
 2192: sub description {
 2193:     my ($token)=@_;
 2194:     my $tag = &get_tag($token);
 2195:     return $insertlist{$tag.'.description'};
 2196: }
 2197: 
 2198: # Returns a list containing the help file, and the description
 2199: sub helpinfo {
 2200:     my ($token)=@_;
 2201:     my $tag = &get_tag($token);
 2202:     return ($insertlist{$tag.'.helpfile'}, $insertlist{$tag.'.helpdesc'});
 2203: }
 2204: 
 2205: sub get_tag {
 2206:     my ($token)=@_;
 2207:     my $tagnum;
 2208:     my $tag=$token->[1];
 2209:     foreach my $namespace (reverse(@Apache::lonxml::namespace)) {
 2210: 	my $testtag = $namespace.'::'.$tag;
 2211: 	$tagnum = $insertlist{"$testtag.num"};
 2212: 	last if (defined($tagnum));
 2213:     }
 2214:     if (!defined($tagnum)) {
 2215: 	$tagnum = $Apache::lonxml::insertlist{"$tag.num"};
 2216:     }
 2217:     return $insertlist{"$tagnum.tag"};
 2218: }
 2219: 
 2220: ############################################################
 2221: #                                           PDF-FORM-METHODS
 2222: 
 2223: =pod
 2224: 
 2225: =item &print_pdf_radiobutton(fieldname, value,  text)
 2226: 
 2227: Returns a latexline to generate a PDF-Form-Radiobutton with Text.
 2228: 
 2229: $fieldname: PDF internalname of the radiobutton
 2230: $value:     Value of radiobutton (read when dumping the PDF data)
 2231: $text:      Text on the rightside of the radiobutton
 2232: 
 2233: =cut
 2234: sub print_pdf_radiobutton {
 2235:     my $result = '';
 2236:     my ($fieldName, $value, $text) = @_;
 2237:     $result .= '\begin{tabularx}{\textwidth}{p{0cm}X}'."\n";
 2238:     $result .= '\radioButton[\symbolchoice{circle}]{'. 
 2239:                $fieldName.'}{10bp}{10bp}{'.$value.'}&'.$text."\n";
 2240:     $result .= '\end{tabularx}' . "\n";
 2241:     $result .= '\hspace{2mm}' . "\n";
 2242:     return $result;
 2243: }
 2244: 
 2245: 
 2246: =pod
 2247: 
 2248: =item &print_pdf_start_combobox(fieldname)
 2249: 
 2250: Starts a latexline to generate a PDF-Form-Combobox with text.
 2251: 
 2252: $fieldname: PDF internal name of the Combobox
 2253: 
 2254: =cut
 2255: sub print_pdf_start_combobox {
 2256:     my $result;
 2257:     my ($fieldName) = @_;
 2258:     $result .= '\begin{tabularx}{\textwidth}{p{2.5cm}X}'."\n";
 2259:     $result .= '\comboBox[]{'.$fieldName.'}{2.3cm}{14bp}{'; # 
 2260: 
 2261:     return $result;
 2262: }
 2263: 
 2264: 
 2265: =pod
 2266: 
 2267: =item &print_pdf_add_combobox_option(options)
 2268: 
 2269: Generates a latexline to add Options to a PDF-Form-ComboBox.
 2270: 
 2271: $option: PDF internal name of the Combobox-Option
 2272: 
 2273: =cut
 2274: sub print_pdf_add_combobox_option {
 2275: 
 2276:     my $result;
 2277:     my ($option) = @_;  
 2278: 
 2279:     $result .= '('.$option.')';
 2280:     
 2281:     return $result;
 2282: }
 2283: 
 2284: 
 2285: =pod
 2286: 
 2287: =item &print_pdf_end_combobox(text) {
 2288: 
 2289: Returns latexcode to end a PDF-Form-Combobox with text.
 2290: 
 2291: =cut
 2292: sub print_pdf_end_combobox {
 2293:     my $result;
 2294:     my ($text) = @_;
 2295: 
 2296:     $result .= '}&'.$text."\\\\\n";
 2297:     $result .= '\end{tabularx}' . "\n";
 2298:     $result .= '\hspace{2mm}' . "\n";
 2299:     return $result;
 2300: }
 2301: 
 2302: 
 2303: =pod
 2304: 
 2305: =item &print_pdf_hiddenField(fieldname, user, domain)
 2306: 
 2307: Returns a latexline to generate a PDF-Form-hiddenField with userdata.
 2308: 
 2309: $fieldname label for hiddentextfield
 2310: $user:    name of user
 2311: $domain:  domain of user
 2312: 
 2313: =cut
 2314: sub print_pdf_hiddenfield {
 2315:     my $result;
 2316:     my ($fieldname, $user, $domain) = @_;
 2317: 
 2318:     $result .= '\textField [\F{\FHidden}\F{-\FPrint}\V{'.$domain.'&'.$user.'}]{'.$fieldname.'}{0in}{0in}'."\n";
 2319: 
 2320:     return $result;
 2321: }
 2322: 
 2323: 1;
 2324: __END__
 2325: 

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