Annotation of loncom/xml/lonxml.pm, revision 1.558

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

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