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

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

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