File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.526: download - view: text, annotated - select for diffs
Tue Dec 6 16:30:19 2011 UTC (12 years, 5 months ago) by dseaton
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
*** empty log message ***

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

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