File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.489: download - view: text, annotated - select for diffs
Mon Nov 24 17:17:52 2008 UTC (15 years, 6 months ago) by jms
Branches: MAIN
CVS tags: HEAD
POD comments added/altered

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

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