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

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

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