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

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

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