File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.505.2.2: download - view: text, annotated - select for diffs
Mon Aug 16 17:29:11 2010 UTC (13 years, 9 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_0_RC1
Diff to branchpoint 1.505: preferred, unified
- Backport 1.509, 1.510, 1.512, 1.513, 1.514.

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

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