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

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

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