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

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

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